我是一个新的C 初学者。我添加了私人访问标识符。为什么会抛出此错误?谢谢
class test
{
private:
test()
{
};
~test()
{
};
public: void call()
{
cout<<"test"<<endl;
} ;
};
错误:
error: 'test::test()' is private|
如果构造函数是 private
,则无法从类本身(或friend
函数外部)构造(定义)类的对象。
也就是说,这是不可能的:
int main()
{
test my_test_object; // This will attempt to construct the object,
// but since the constructor is private it's not possible
}
如果要将对象的构造(创建)限制在因子函数上很有用。
例如
class test
{
// Defaults to private
test() {}
public:
static test create()
{
return test();
}
};
然后您可以像
一样使用它test my_test_object = test::create();
如果驱动器也为 private
,则不会破坏对象(当变量(对象)寿命结束时发生,例如,当变量在函数结束时出现范围时)。