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

时间:2012-03-18 08:02:24

标签: c++ interface concept

  

可能重复:
  Preferred way to simulate interfaces in C++

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

3 个答案:

答案 0 :(得分:98)

C ++没有内置的接口概念。您可以使用仅包含abstract classespure 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 () {}