我的程序如下:
class xxx{
public: explicit xxx(int v){cout<<"explicit constructor called"<<endl;}
xxx(int v,int n=0){cout<<"default constructor called"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1(20); //should call the explicit constructor
xxx x2(10,20); //should call the constructor with two variables
return 0;
}
当我编译时,我得到错误:-"重载的xxx(int)调用不明确"
我知道编译器发现两个构造函数签名都相等,因为我在默认情况下生成了一个参数"0"。
有没有什么方法可以让编译器处理不同的签名,从而使程序能够成功编译?
您只需要一个构造函数
class xxx
{
public:
explicit xxx(int v, int n=0)
{
cout << "default constructor called" << endl;
}
};
然后您可以初始化XXX个对象:
xxx x1(20); //should call the explicit constructor
xxx x2(10,20); //should call the construct
您有两个选择:
删除其中一个构造函数:
class xxx
{
public:
explicit xxx(int v, int n = 0); // don't forget explicit here
};
删除默认参数:
class xxx
{
public:
explicit xxx(int v);
xxx(int v,int n);
};
无论哪种方式,main()
中的代码都可以工作。选择权在你(而且主要是主观品味的问题)。