C++ 如何删除默认构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10474417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:06:55  来源:igfitidea点击:

How to delete the default constructor?

c++

提问by Yukio Fukuzawa

Sometimes I don't want to provide a default constructor, nor do I want the compiler to provide a system default constructor for my class. In C++ 11 I can do thing like:

有时我不想提供默认构造函数,也不希望编译器为我的类提供系统默认构造函数。在 C++ 11 中,我可以做这样的事情:

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

But currently my lecturer doesn't allow me to do that in my assignment. The question is: prior to C++ 11, is there any way to tell the compiler to stop implicitly provide a default constructor?

但是目前我的讲师不允许我在我的作业中这样做。问题是:在 C++ 11 之前,有没有办法告诉编译器停止隐式提供默认构造函数?

回答by vidit

I would say make it private.. something like

我会说把它设为私有.. 类似

class MyClass
{
private:
    MyClass();
}

and no one(from outside the class itself or friend classes) will be able to call the default constructor. Also, then you'll have three options for using the class: either to provide a parameterized constructor or use it as a utility class (one with static functions only) or to create a factory for this type in a friend class.

并且没有人(来自类本身或朋友类之外)将能够调用默认构造函数。此外,您将有三个使用该类的选项:提供参数化构造函数或将其用作实用程序类(一个仅具有静态函数的类)或在友元类中为此类型创建工厂。

回答by Edward Strange

Sure. Define your own constructor, default or otherwise.

当然。定义您自己的构造函数,默认或其他。

You can also declare it as private so that it's impossible to call. This would, unfortunately, render your class completely unusable unless you provide a static function to call it.

您也可以将其声明为私有,以便无法调用。不幸的是,这会使您的类完全无法使用,除非您提供一个静态函数来调用它。

回答by fafrd

Since c++11, you can set constructor = delete. This is useful in conjunction with c++11's brace initialization syntax {}.

从 c++11 开始,您可以设置 constructor = delete。这与 c++11 的大括号初始化语法结合使用很有用{}

For example:

例如:

struct foo {
  int a;
  foo() = delete;
};

foo f{}; // error use of deleted function foo::foo()
foo f{3}; // OK

see https://en.cppreference.com/w/cpp/language/default_constructor#Deleted_implicitly-declared_default_constructor

https://en.cppreference.com/w/cpp/language/default_constructor#Deleted_implicitly-declared_default_constructor

回答by Simon Oelmann

Additionally to declaring the default constructor private, you could also throw an exception when somebody tries to call it.

除了将默认构造函数声明为私有之外,您还可以在有人尝试调用它时抛出异常。

class MyClass
{
  private:
    MyClass() 
    {
      throw [some exception];
    };
}