不从派生类调用基类构造函数
假设我有一个基类:
class baseClass
{
public:
baseClass() { };
};
和一个派生类:
class derClass : public baseClass
{
public:
derClass() { };
};
当我创建 derClass 的实例时,将调用 baseClass
的构造函数。我怎样才能防止这种情况发生?
Say I have a base class:
class baseClass
{
public:
baseClass() { };
};
And a derived class:
class derClass : public baseClass
{
public:
derClass() { };
};
When I create an instance of derClass
the constructor of baseClass
is called. How can I prevent this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想要创建一个受保护的(可能为空)默认构造函数,该构造函数将由派生类使用:
这将阻止任何外部代码使用默认
Base
构造函数(因此不会初始化a< /code> 正确)。您只需要确保在
Derived
构造函数中初始化所有Base
字段即可。You might want to create a protected (possibly empty) default constructor which would be used by the derived class:
This will block any external code from using default
Base
constructor (and thus not initializinga
properly). You just need to make sure you initialize all theBase
fields in theDerived
constructor as well.创建一个额外的空构造函数。
Make an additional empty constructor.
基类实例是任何派生类实例的组成部分。如果成功构造派生类实例,根据定义,您必须构造所有基类和成员对象,否则派生对象的构造将会失败。构造基类实例涉及调用其构造函数之一。
这是继承在 C++ 中如何工作的基础。
A base class instance is an integral part of any derived class instance. If you successfully construct a derived class instance you must - by definition - construct all base class and member objects otherwise the construction of the derived object would have failed. Constructing a base class instance involves calling one of its constructors.
This is fundamental to how inheritance works in C++.
工作程序
输出示例
Sample working program
output