所以我有两个抽象类; 一个定义如下:
class Bindable
{
virtual void Bind() const = 0;
virtual void UnBind() const = 0;
};
Run Code Online (Sandbox Code Playgroud)
另一个定义如下:
class Disposable
{
virtual void Dispose() = 0;
}
Run Code Online (Sandbox Code Playgroud)
我让这个Component类继承自他们的虚拟方法,如下所示:
class Component : public virtual Bindable, public virtual Disposable
{
//method implementations...
void Bind() const;
void UnBind() const;
void Dispose();
}
Run Code Online (Sandbox Code Playgroud)
所以:我做得对吗?我是否需要虚拟地继承这两个抽象类?还是我错过了什么?(我还没有遇到过多重继承的情况,所以我还不习惯......)
你不需要在这里虚拟地继承.只有钻石继承时才需要虚拟继承(请参阅此处的 C++ FAQ ).在这种情况下,您可以简单地继承,而不必担心具有多个实例Bindable或Disposable继承层次结构中的多个实例.
另一件事,Bindable并Disposable应可能有虚析构函数,使他们正确地摧毁如果类是通过两种接口的破坏.所以你应该添加它Disposable
virtual ~Disposable() { }
Run Code Online (Sandbox Code Playgroud)
这个 Bindable
virtual ~Bindable() { }
Run Code Online (Sandbox Code Playgroud)