R_K*_*app 6 c++ constructor private most-vexing-parse
我上课了
class A
{
public:
class Key
{
Key() {}
Key(Key const &) {}
};
A(Key key, int a = 5) {}
};
Run Code Online (Sandbox Code Playgroud)
构造函数Key是私有的,因此没有人应该能够构造一个对象A.但是,使用以下代码:
int main() {
A a(A::Key()); // this compiles !!!
A a2(A::Key(), 5); // this doesn't
// somehow defaulting the argument causes the private constructor
// to be OK - no idea why
return 0;
}
Run Code Online (Sandbox Code Playgroud)
通过int a在我的构造函数中使用默认参数,编译器很乐意编译我的用法,A::Key()尽管它是私有的.但是,如果我明确地给出了一个值a,那么编译器会正确识别我正在尝试使用私有构造函数并输出错误.为什么是这样?有没有办法强制编译器在第一个例子中出错?
请看这里的实例.
这是因为最令人烦恼的解析.
A a(A::Key());
Run Code Online (Sandbox Code Playgroud)
不创建A命名a并使用临时构造它A::Key.它创建了一个函数a,该函数返回一个A并且将一个未命名的指针指向返回a的函数A::Key.
如果向其中添加一对括号,则会出现编译器错误
A a((A::Key()));
Run Code Online (Sandbox Code Playgroud)
你试图调用私有构造函数.或者,您可以使用统一初始化,这也可以消除歧义并导致编译错误
A a(A::Key{});
Run Code Online (Sandbox Code Playgroud)