【发布时间】: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