#include <iostream>
using namespace std;
class Test{
private:
Test(int a, int b=0)
{
cout << "private constructor\n";
}
public:
Test(int a)
{
cout << "public constructor\n";
}
};
int main()
{
Test t(1);
}
候选人当我试图编译代码gcc
说:编译器提供私人构造为程序代码中
test.cpp: In function ‘int main()’:
test.cpp:20:10: error: call of overloaded ‘Test(int)’ is ambiguous
Test t(1);
^
test.cpp:12:2: note: candidate: Test::Test(int)
Test(int a)
^
test.cpp:7:2: note: candidate: Test::Test(int, int)
Test(int a, int b=0)
^
test.cpp:5:7: note: candidate: Test::Test(const Test&)
class Test{
^
和clang
说:
test.cpp:20:7: error: call to constructor of 'Test' is ambiguous
Test t(1);
^~
test.cpp:7:2: note: candidate constructor
Test(int a, int b=0)
^
test.cpp:12:2: note: candidate constructor
Test(int a)
^
test.cpp:5:7: note: candidate is the implicit copy constructor
class Test{
^
1 error generated.
是什么的原因歧义?由于Test(int,int)
是私人的,因此不应该在Test t(1)
中调用它。一个可能的答案是(我最初想的),它使得两个相同的构造函数签名成为可能,即Test()
只能在私有构造函数中调用一个int
。但在程序代码Test t(1)
只适用于公共构造函数,所以它不应该提供私有构造函数作为候选。为什么这么说?
同样的原因,因为这:http://stackoverflow.com/questions/39042240/why-is-a-public-const-method-not-被称为什么时候非const-one-is-private/39042574#39042574 – NathanOliver