如何禁止使用C ++中的默认构造函数? [英] How to forbid the use of the default constructor in C++?
问题描述
我不想让我的程序创建一个对象而不传递参数到构造函数。
有办法吗?
当你声明任何其他构造函数时,编译器不会为你生成默认构造函数。如果你指定了一个默认的无参数构造函数,你可以将它设为private。
请记住,编译器可以自动为类生成这4个成员函数。 / p>
- 默认没有参数构造函数
- 默认析构函数
- default no argument constructor
- default destructor
- copy constructor
- assignment operator
$ b 但是如果你已经声明了一个你自己,即,如果你自己声明一个构造函数,它不会创建默认的构造函数。如果没有声明任何其他3,编译器可以生成它们。
编辑:请注意,此信息适用于C ++ 03,但它是在C ++ 11中不同,Matthieu M.在评论中提到。
I don't want to make it possible in my program to create an object without passing arguments to the constructor.
Is there a way?
When you declare any other constructor, the compiler will not generate the default constructor for you. If you have specified a default no-argument constructor, you can make it private.
Remember that the compiler can automatically generate each of these 4 member functions for a class.
But it will not generate a default one if you have declared one yourself, i.e., if you declared a constructor yourself, it will not create the default constructor. If you didn't declare any of the other 3 though, the compiler can generate them.
edit: Note that this information applies to C++03, but it is different in C++11 as Matthieu M. mentions in the comments.
这篇关于如何禁止使用C ++中的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!