我很想知道C ++中是否存在接口,因为在Java中,设计模式的实现主要是通过接口将类解耦。有没有类似的方法在C ++中创建接口呢?
答案 0 :(得分:98)
C ++没有内置的接口概念。您可以使用仅包含abstract classes的pure virtual functions来实现它。由于它允许多重继承,你可以继承这个类来创建另一个类,然后在其中包含这个接口(我的意思是,对象接口:))。
示例示例是这样的 -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
答案 1 :(得分:13)
C ++中没有接口的概念,
您可以使用 Abstract class 来模拟行为
抽象类是一个至少有一个纯虚函数的类,一个不能创建抽象类的任何实例,但你可以创建指针和引用它。此外,从抽象类继承的每个类都必须实现纯虚函数,以便可以创建它的实例。
答案 2 :(得分:11)
接口只不过是C ++中的纯抽象类。理想情况下,此接口 class
应仅包含纯virtual
公共方法和static const
数据。例如:
class InterfaceA
{
public:
static const int X = 10;
virtual void Foo() = 0;
virtual int Get() const = 0;
virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}