C ++中类的定义和访问标识符

时间:2019-03-21 13:16:49

标签: c++ class

我是一名新的c ++初学者。我添加了私有访问标识符。为什么会引发此错误?谢谢

class test
{
    private:
    test()
    {
    };
    ~test()
    {

    };
    public: void call()
    {
        cout<<"test"<<endl;
    } ;
};

错误:

error: 'test::test()' is private|

1 个答案:

答案 0 :(得分:2)

如果构造函数是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,则对象不能被破坏(当变量(对象)生存期结束时发生,例如,当变量在函数末尾超出范围时发生) )。