问题描述
我想要一个 C++ Interface
,它在继承时必须被覆盖(如果可能的话).到目前为止,我有以下内容:
I would like to have a C++ Interface
that must be overridden (if this is possible) when inherited. So far, I have the following:
class ICommand{
public:
// Virtual constructor. Needs to take a name as parameter
//virtual ICommand(char*) =0;
// Virtual destructor, prevents memory leaks by forcing clean up on derived classes?
//virtual ~ICommand() =0;
virtual void CallMe() =0;
virtual void CallMe2() =0;
};
class MyCommand : public ICommand
{
public:
// Is this correct?
MyCommand(char* Name) { /* do stuff */ }
virtual void CallMe() {}
virtual void CallMe2() {}
};
我特意留下了我认为应该在ICommand
中实现构造函数/析构函数的方式.我知道如果我删除评论,它将无法编译.请有人:
I have purposely left how I think the constructor/destructor's should be implemented in ICommand
. I know if I remove the comments, it will not compile. Please could someone:
- 告诉我如何在
ICommand
中声明构造函数/析构函数,以及如何在MyCommand
中使用它们 - 我是否在
ICommand
中正确设置,以便MyCommand
必须覆盖CallMe
和CallMe2
.莉>
- Show me how to declare the constructor/destructor's in
ICommand
and how they are meant to be used inMyCommand
- Have I set things up correctly in
ICommand
so thatMyCommand
must overrideCallMe
andCallMe2
.
推荐答案
C++ 不允许使用虚拟构造函数.一个简单的实现(没有虚拟构造函数)看起来像这样:
C++ does not allow for virtual constructors. A simple implementation (without the virtual constructor) would look something like this:
class ICommand {
public:
virtual ~ICommand() = 0;
virtual void callMe() = 0;
virtual void callMe2() = 0;
};
ICommand::~ICommand() { } // all destructors must exist
请注意,即使是纯虚拟析构函数也必须被定义.
Note that even a pure virtual destructor must be defined.
具体的实现与您的示例完全一样:
A concrete implementation would look exactly like your example:
class MyCommand : public ICommand {
public:
virtual void callMe() { }
virtual void callMe2() { }
};
您有几个选项对于构造函数.一种选择是禁用 ICommand
的默认构造函数,这样子类将必须实现一个调用你的 ICommand 构造函数的构造函数:
You have a couple of options for the constructor. One option is to disable the default constructor for ICommand
, so that subclasses will have to implement a constructor that calls your ICommand constructor:
#include <string>
class ICommand {
private:
const std::string name;
ICommand();
public:
ICommand(const std::string& name) : name(name) { }
virtual ~ICommand() = 0;
virtual void callMe() = 0;
virtual void callMe2() = 0;
};
ICommand::~ICommand() { } // all destructors must exist
一个具体的实现现在看起来像这样:
A concrete implementation would now look something like this:
class MyCommand : public ICommand {
public:
MyCommand(const std::string& name) : ICommand(name) { }
virtual void callMe() { }
virtual void callMe2() { }
};
这篇关于C++ 抽象基类构造函数/析构函数 - 一般正确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!