C++ - 如果构造函数是私有的,这会做什么?
在下面的代码中,为什么编译器不抱怨 mClass2?
class CMyClass{
private:
CMyClass(){}
};
void TestMethod(){
CMyClass mClass1; //Fails.
CMyClass mClass2(); //Works.
}
In the code below, why does the compiler not complain for mClass2?
class CMyClass{
private:
CMyClass(){}
};
void TestMethod(){
CMyClass mClass1; //Fails.
CMyClass mClass2(); //Works.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为您刚刚声明了一个零参数的函数
mClass2
,它返回一个CMyClass
。这是一个有效的选项,因为可能存在该函数可以访问的静态 CMyClass 实例。请注意,CMyClass
仍然有一个公共复制构造函数。(为了说服自己,将此模块编译为汇编程序,并观察注释掉
CMyClass mClass2();
行会产生相同的输出。)Because you've just declared a function
mClass2
of zero arguments that returns aCMyClass
. That's a valid option since there could be, say, astatic CMyClass
instance which that function has access to. Note thatCMyClass
still has a public copy constructor.(To convince yourself, compile this module to assembler and observe that commenting out the line
CMyClass mClass2();
produces the same output.)因为它是声明一个函数,而不是像你想象的那样调用构造函数。
这被称为最令人烦恼的解析 在 C++ 中。
声明一个函数
mClass2()
,它不带参数并返回CMyClass
Because it is declaring a function and not calling the constructor as you think.
This is called as the Most Vexing Parse in c++.
declares a function
mClass2()
which takes no parameter and returnsCMyClass
第二个是函数声明。
The second one is a function declaration.
人们应该使用 {} 括号转向 C++0x/C++11 中的统一语法初始化,从而消除此问题。
C类{};
http://www2.research.att.com/~ bs/C++0xFAQ.html#uniform-init
People ought to move to the uniform syntax initialization in C++0x/C++11 using the {} brackets instead which removes this issue.
Class C{};
http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init