gpt4 book ai didi

c++ - 如果抽象基类是一个接口(interface),是否必须在派生类构造函数中调用基类构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:31 26 4
gpt4 key购买 nike

class AbstractQuery {
virtual bool isCanBeExecuted()=0;
public:
AbstractQuery() {}
virtual bool Execute()=0;
};

class DropTableQuery: public AbstractQuery {
vector< std::pair< string, string> > QueryContent;
QueryValidate qv;
public:
explicit DropTableQuery(const string& qr): AbstractQuery(), qv(qr) {}
bool Execute();
};

派生类构造函数中是否需要调用基类构造函数?

最佳答案

不,事实上因为基类没有必要有一个显式定义的构造函数(但要确保你有一个虚析构函数)。

所以对于一个典型的界面,你可以有这样的东西:

class MyInterface {
public:
virtual ~MyInterface() {}
virtual void execute() = 0;
};

编辑:这是你应该有一个虚拟析构函数的原因:

MyInterface* iface = GetMeSomeThingThatSupportsInterface();
delete iface; // this is undefined behaviour if MyInterface doesn't have a virtual destructor

关于c++ - 如果抽象基类是一个接口(interface),是否必须在派生类构造函数中调用基类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/270592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com