如何删除默认构造函数

如何删除默认构造函数

本文介绍了如何删除默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

解决方案

我会说,使它私人..像

  class MyClass 
{
private:
MyClass();
}

并且没有任何人(从类本身或朋友类外部)调用默认构造函数。另外,你将有三个选项来使用类:提供一个参数化的构造函数,或者使用它作为一个实用程序类(只有一个静态函数),或者在朋友类中创建这个类型的工厂。 / p>

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:

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?

解决方案

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 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.

这篇关于如何删除默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:23