che*_*r89 4 c++ oop constructor abstract-class class-design
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();
};
Run Code Online (Sandbox Code Playgroud)
是否有必要在派生类构造函数中调用基础构造函数?
不,实际上因为基类没有必要有一个显式定义的构造函数(尽管确保你有一个虚拟析构函数).
因此,对于典型的界面,您可以使用以下内容:
class MyInterface {
public:
virtual ~MyInterface() {}
virtual void execute() = 0;
};
Run Code Online (Sandbox Code Playgroud)
编辑:这是你应该有一个虚拟析构函数的原因:
MyInterface* iface = GetMeSomeThingThatSupportsInterface();
delete iface; // this is undefined behaviour if MyInterface doesn't have a virtual destructor
Run Code Online (Sandbox Code Playgroud)