【问题标题】:derived constructor without calling base constructor不调用基础构造函数的派生构造函数
【发布时间】:2022-12-03 00:06:47
【问题描述】:

我是 OOP 新手,碰巧知道当调用派生类的构造函数(或解构函数)时,也会调用基类的构造函数(或解构函数)。但是,如果我不想调用基本构造函数/解构函数怎么办?

class Base{
    public:
    
    Base(){
        cout<<"Base constructor called\n";
    }
    ~Base(){
        cout<<"Base deconstructor called\n";
    }
};
class Derived: public Base{
    public:
    Derived(){
        cout<<"Derived constructor called\n";
    }
    ~Derived(){
        cout<<"Derived deconstructor called\n";
    }
};
int main()
{
    Derived* obj_a = new Derived;
    delete obj_a;

    return 0;
}

结果是:

Base constructor called
Derived constructor called
Derived deconstructor called
Base deconstructor called

【问题讨论】:

  • 我认为你有 XY 问题。你试图解决什么现实生活中的问题(通过省略基本的 ctor/dtor 调用)?
  • “但是,如果我不想调用基础构造函数/解构函数怎么办,那我该怎么办?” - 为什么?你你的程序行为不可预测?这是XY problem吗?
  • 您可以向基类添加一个构造函数,该构造函数采用一个特殊的标记类型参数,这意味着“不要初始化任何东西”。
  • 那么你的设计是有缺陷的,应该重做。

标签: c++ oop inheritance


【解决方案1】:

这不是java; base ctor/dtor 将始终被调用,因为必须建立 base 的不变量并且必须执行销毁类所需的操作。如果您需要以某种方式从后代向基地发出某些特定资源不应被释放的信号,则需要使其成为基地状态的一部分;但通常它被认为是一个坏模式。

【讨论】:

    猜你喜欢
    • 2018-07-21
    • 2016-07-19
    • 2018-07-16
    • 2015-08-18
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2020-11-28
    • 2011-05-03
    相关资源
    最近更新 更多