ambiguous constructor call while object creation

五迷三道 提交于 2019-12-22 12:25:26

问题


My program is as follows:

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;
  }

When I compile I get the error:- "call of overloaded âxxx(int)â is ambiguous"

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?


回答1:


You just need one constructor

class xxx
{
public:
    explicit xxx(int v, int n=0)
    {
       cout << "default constructor called" << endl;
    }
};

Then you could initialize XXX objects:

xxx x1(20);    //should call the explicit constructor
xxx x2(10,20); //should call the construct



回答2:


You have 2 choices:

Remove one of the constructors:

class xxx
{
public:
    explicit xxx(int v, int n = 0); // don't forget explicit here
};

Remove the default parameter:

class xxx
{
public:
    explicit xxx(int v);
    xxx(int v,int n);
};

Either way the code in main() will work. The choice is yours (and is mostly a matter of a subjective taste).



来源:https://stackoverflow.com/questions/18356150/ambiguous-constructor-call-while-object-creation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!