【发布时间】:2018-03-11 11:53:16
【问题描述】:
我有课
class A
{
public:
class Key
{
Key() {}
Key(Key const &) {}
};
A(Key key, int a = 5) {}
};
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;
}
通过在我的构造函数中使用int a 的默认参数,编译器很高兴地编译了我对A::Key() 的使用,尽管它是私有的。但是,如果我明确地为 a 赋值,编译器会正确识别出我正在尝试使用私有构造函数并出错。为什么是这样?是否有办法强制编译器在第一个示例中也出错?
请参阅here 以获取实时示例。
【问题讨论】:
标签: c++ constructor private most-vexing-parse