没有。 (反正不是这样)
您可能会被其他语言(如 Java、C#、ActionScript 等)的处理方式误导。
在 C++ 中,多重继承和虚拟类的管理方式使得接口(在其他语言中使用)过时了。在那些其他语言中,接口用于解决由于缺少多重继承而引发的问题(好坏,这是一种选择)。
所以如果你想做的只是提供一个通用接口和一些提供默认实现的虚拟方法,只需在基类中实现:
class Interface
{
virtual void myfunction() { /*...*/ } //default implementation
virtual void yourFunction() = 0 ; // this one HAVE TO be implemented by the user
};
class Derived
: public Interface // don't need another class
{
// myfunction is implemented by base
void yourFunction(); // have to implement yourFunction
};
class DerivedB
: public Interface // don't need another class
{
void myFunction(); // myfunction is implemented by base but we implement it for this specific class
void yourFunction(); // have to implement yourFunction
};
但是,如果您想提供多个具有相同接口的基类,则认为您的接口类是其他类的基类
// in this order
class Interface
{
virtual void myfunction() = 0;
};
class BaseA : public Interface
{
// here "virtual" is optional as if the parent is virtual, the child is virtual too
virtual void myfunction() {/*...*/}; // BaseA specific implementation
};
class BaseB : public Interface
{
virtual void myfunction() {/*...*/}; // BaseB specific implementation
};
然而,有一种不太容易阅读(阅读:不推荐)的方式来提供默认实现,但强制用户明确说明他是否想使用它。它利用了这样一个事实,即即使是纯虚函数也可以具有可以调用的默认实现:
class Interface
{
virtual void myfunction() { /*...*/ } // default implementation
virtual void yourFunction() = 0 ; // this one HAVE TO be implemented by the user BUT provide a default implementation!
};
// in Interface.cpp
void Interface::yourFunction() // default implementation of the virtual pure function
{ /*...*/ }
// in Derived.h
class DerivedA
: public Interface // don't need another class
{
// myfunction is implemented by base
void yourFunction(); // have to implement yourFunction -- DerivedA specific
};
class DerivedB
: public Interface // don't need another class
{
void myFunction(); // myfunction is implemented by base but we implement it for this specific class
void yourFunction() { Interface::yourFunction(); } // uses default implementation of yourFunction, hidden but existing
};
但不要这样做。