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?
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
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.