删除的默认构造函数应该在 Public 还是 Private 中?

Should the deleted default constructor be in Public or Private?

我不得不删除默认构造函数以确保始终使用参数化构造函数。 那时我想知道我删除的默认构造函数是否应该在 public 或私有访问说明符下。

我刚刚写了一个示例代码来测试这个。我试图访问已删除的默认构造函数。

class A
{
public:
    A(const int val)
    {
        assign = val;
    }
private:
    A() = delete;
    int assign;
};

int main()
{
    A obj1(5);
    A obj2;
}

main.cpp: In function ‘int main()’:

main.cpp:35:7: error: ‘A::A()’ is private within this context

A obj2;

main.cpp:28:5: note: declared private here

A() = delete;

main.cpp:35:7: error: use of deleted function ‘A::A()’

A obj2;

main.cpp:28:5: note: declared here

A() = delete;

最好用public访问定义默认构造函数:

class A
{
public:
    A() = delete;
    A(const int &val) : assign(val){}
private:
    int assign;
};

现在你得到一个更好的错误:

int main (void){
    A obj;
}
  • 您不需要使用已删除的构造函数。
class A
{
public:
    A(const int &val) : assign(val){}
private:
    int assign;
};
int main()
{
    A a;
    return 0;
}

给出 error: no matching function for call to ‘A::A()’

class A
{
public:
    A() = delete;
    A(const int &val) : assign(val){}
private:
    int assign;
};
int main()
{
    A a;
    return 0;
}

给出 error: use of deleted function ‘A::A()’

  • 关于删除的使用,它可能对继承有用。
class A
{
public:
    A() : assign(0){}
    A(int val) : assign(val){}
private:
    int assign;
};

class B : public A
{
public:
    B() = delete;
    B(int val) : A(val){};
};

class C : public A
{

};

class D : public A
{
public:
    D() = delete;
};


int main()
{
    A a1; //works
    A a2(5); //works

    //B b1; -- does not work : error: use of deleted function ‘B::B()’
    B b2(3); //works

    C c1; //works, creates a default ctor
    //C c2(7); -- does not work : no matching function for call to ‘C::C(int)’

    //D d1; -- does not work :error: use of deleted function ‘D::D()’
    //D d2(2); -- does not work: error: no matching function for call to ‘D::D(int)’
    return 0;
}

注意D不能被实例化。虽然没用:)