在C++中,是否可以使用base和派生类实现单个接口?
例如:
class Interface { public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0; }; class Base { public: virtual void BaseFunction(){} }; class Derived : public Base, public Interface { public: void DerivedFunction(){} }; void main() { Derived derived; }
这会失败,因为Derived无法实例化.就编译器而言,从未定义Interface :: BaseFunction.
到目前为止,我发现的唯一解决方案是在Derived中声明传递函数
class Derived : public Base, public Interface { public: void DerivedFunction(){} void BaseFunction(){ Base::BaseFunction(); } };
有没有更好的解决方案?
编辑:如果重要,这是我使用MFC对话框的现实问题.
我有一个从CDialog派生的对话类(MyDialog可以说).由于依赖性问题,我需要创建一个抽象接口(MyDialogInterface).使用MyDialogInterface的类需要使用特定于MyDialog的方法,但还需要调用CDialog :: SetParent.我刚刚通过创建MyDialog :: SetParent并将其传递给CDialog :: SetParent来解决它,但是想知道是否有更好的方法.
C++没有注意到从Base继承的函数已经实现BaseFunction
:该函数必须在派生自的类中显式实现Interface
.这样改变:
class Interface { public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0; }; class Base : public Interface { public: virtual void BaseFunction(){} }; class Derived : public Base { public: virtual void DerivedFunction(){} }; int main() { Derived derived; }
如果您希望只能实现其中一个,则Interface
可以分成两个接口:
class DerivedInterface { public: virtual void DerivedFunction() = 0; }; class BaseInterface { public: virtual void BaseFunction() = 0; }; class Base : public BaseInterface { public: virtual void BaseFunction(){} }; class Derived : public DerivedInterface { public: virtual void DerivedFunction(){} }; class Both : public DerivedInterface, public Base { public: virtual void DerivedFunction(){} }; int main() { Derived derived; Base base; Both both; }
注意:main必须返回int
注意:最好保留virtual
在基础中虚拟的派生中的成员函数前面,即使它不是严格要求的.