开发者

C++ Scoping and ambiguity in constructor overloads

开发者 https://www.devze.com 2022-12-31 03:05 出处:网络
I\'ve tried the following code snippet in 3 different compilers (G++, clang++, CL.exe) and they all report to me that they cannot disambiguate the overloaded constructors. Now, I know how I could modi

I've tried the following code snippet in 3 different compilers (G++, clang++, CL.exe) and they all report to me that they cannot disambiguate the overloaded constructors. Now, I know how I could modify the call to the constructor to make it pick one or the other (either make explicit that the second argument is a unsigned literal value or explicitly cast it).

However, I'm curious why the compi开发者_运维技巧ler would be attempting to choose between constructors in the first place given that one of the constructors is private and the call to the constructor is happening in the main function which should be outside the class's scope.

Can anyone enlighten me?

class Test
{
private:
        Test(unsigned int a, unsigned int *b) { }
public:
        Test(unsigned int a, unsigned int b) { }
};

int main()
{
        Test t1 = Test(1,0);  // compiler is confused
}


In C++, accessibility to class members doesn't influence the other language semantics. Instead, any invalid access causes a program to be ill-formed.

In other words, there is accessibility and visibility. The Standard has it straight

It should be noted that it is access to members and base classes that is controlled, not their visibility. Names of members are still visible, and implicit conversions to base classes are still considered, when those members and base classes are inaccessible. The interpretation of a given construct is established without regard to access control. If the interpretation established makes use of inaccessible member names or base classes, the construct is ill-formed.


The compiler does not attempt to select an overloaded function or constructor by its visibility.


It is more that the compiler will not refuse a candidate function even if it is marked as private. This means changing visability of a member will not changing existing code.


As for your second question, overload resolution happens before the test for visibility.

As for the first, you need to indicate to the compiler that the 0 is an unsigned int. As far as the compiler is concerned, the conversion from integer 0 to unsigned int is no better than the conversion from integer 0 to pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消