模糊的构造函数调用,而对象创建 [英] ambiguous constructor call while object creation
本文介绍了模糊的构造函数调用,而对象创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的计划如下:
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)是不明确的
When I compile I get the error:- "call of overloaded âxxx(int)â is ambiguous"
我知道编译器会发现 constructor signature等于 '0'。
I know that compiler finds both constructor signature equal since I made an argument by default '0'.
有什么方法编译器可以处理不同的签名,并且程序会成功编译?
Is there any way that compiler can treat the signatures different and the program would compile successfully?
推荐答案
您有两个选择:
删除其中一个构造函数:
Remove one of the constructors:
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()中的代码
将工作。选择是你的(主要是一个主观的味道)。
Either way the code in main()
will work. The choice is yours (and is mostly a matter of a subjective taste).
这篇关于模糊的构造函数调用,而对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文