为什么要明确删除构造函数? [英] why explicitly delete the constructor?

查看:398
本文介绍了为什么要明确删除构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时/为什么要显式删除我的构造函数?假设原因是为了防止其使用,为什么不让它 private

When/why would I want to explicitly delete my constructor? Assuming the reason is to prevent its usage, why not just make it private?

class Foo
{ 
  public: 
    Foo() = delete; 
};


$ b

谢谢!

Thanks!

推荐答案

如何:

//deleted constructor
class Foo
{ 
  public: 
    Foo() = delete;     
  public:
    static void foo();
};

void Foo::foo()
{
   Foo f;    //illegal
}

对比

//private constructor
class Foo
{ 
  private: 
    Foo() {}     
  public:
    static void foo();
};

void Foo::foo()
{
   Foo f;    //legal
}

它们基本上是不同的。 private 告诉你只有类的成员可以调用该方法或访问该变量(当然是朋友)。在这种情况下,该类(或任何其他成员)的 static 方法调用 private 构造函数的类。

They're basically different things. private tells you that only members of the class can call that method or access that variable (or friends of course). In this case, it's legal for a static method of that class (or any other member) to call a private constructor of a class. This doesn't hold for deleted constructors.

范例这里

这篇关于为什么要明确删除构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆