#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