108

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

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

4

3 回答 3

150

C++ 没有内置的接口概念。您可以使用仅包含纯虚函数的抽象类来实现它。因为它允许多重继承,你可以继承这个类来创建另一个类,然后在其中包含这个接口(我的意思是,对象接口:))。

一个例子是这样的 -

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;
}
于 2012-03-18T08:03:14.253 回答
17

“接口”相当于 C++ 中的纯抽象类。理想情况下,这个接口 class应该只包含virtual public方法和static const数据成员。例如:

struct MyInterface
{
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~MyInterface() = 0;
};
MyInterface::~MyInterface () {}
于 2012-03-18T08:04:48.383 回答
16

C++ 中没有接口的概念,
您可以使用抽象类来模拟行为。
抽象类是具有至少一个纯虚函数的类,一个不能创建抽象类的任何实例,但您可以创建指向它的指针和引用。此外,从抽象类继承的每个类都必须实现纯虚函数才能创建它的实例。

于 2012-03-18T08:04:09.993 回答