c++ 请问下构造函数不能带参数?
来源:百度知道 编辑:UC知道 时间:2024/05/25 19:50:38
#include<iostream>
#include<string>
using namespace std;
class num1
{
public:
num1(int a,int b)
{
cout<<"hello"<<endl;
}
};
void main()
{
num1 num;
}
//---把参数去掉就能编译通过。请问下构造函数不能带参数?
#include<string>
using namespace std;
class num1
{
public:
num1(int a,int b)
{
cout<<"hello"<<endl;
}
};
void main()
{
num1 num;
}
//---把参数去掉就能编译通过。请问下构造函数不能带参数?
num1 num(1,2);
调用的时候要按照你声明的格式写~
呵呵,不是不能带
如果你定义了带参数的构造函数
而又不带参数去定义,这个问题就出现了
因为系统不会再帮你生成默认构造函数了
加个
num1(){}
在类里
你定义的时候既然带参数,你声明的时候也要带参数。num1 num(数字,数字);
你定义构造函数的时候可以多个(重载),编译器据此(参数个数和类型)来判断你调用的是哪个构造函数。
#include<iostream>
#include<string>
using namespace std;
class num1
{
public:
num1(int a,int b)
{
cout<<"hello"<<endl<<"a="<<a<<endl<<"b="<<b<<endl;
}
};
void main()
{
num1 num(1,2);//赋初值
}
可以,程序这样改就可以通过