如何在 C + + 中实现接口?

可能的复制品:
在 C + + 中模拟接口的首选方法

我很好奇 C + + 中是否有接口,因为在 Java 中,设计模式的实现主要是通过接口解耦类。那么在 C + + 中是否有类似的创建接口的方法呢?

200019 次浏览

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

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;
}

There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.

An "Interface" is equivalent to a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data members. For example:

struct MyInterface
{
static const int X = 10;


virtual void Foo() = 0;
virtual int Get() const = 0;
virtual inline ~MyInterface() = 0;
};
MyInterface::~MyInterface () {}