问题
#include<iostream>
using namespace std;
class abc{
int a;
public: abc() { } //do nothing constructor
abc(int x=6){ a=x;} //constructor with default argument
};
main()
{
abc a;
....
}
my question is which constructor will be invoked in this case ? Please explain
回答1:
This will not compile due to the ambiguity as you can see here
prog.cpp:8:7: warning: ISO C++ forbids declaration of ‘main’ with no type [-Wreturn-type]
prog.cpp: In function ‘int main()’:
prog.cpp:10:11: error: call of overloaded ‘abc()’ is ambiguous
prog.cpp:10:11: note: candidates are:
prog.cpp:6:12: note: abc::abc(int)
prog.cpp:5:12: note: abc::abc()
回答2:
The call you are making to the constructor is ambiguous. The compiler cannot know which constructor to call since one of your constructor contains a default argument.
Instead, try removing the default value to the argument.
来源:https://stackoverflow.com/questions/17770113/ambiguity-in-c-constructor-when-a-constructor-with-default-argument-exists