28

可能重复:
如何在 C++ 中声明接口?
c++中的java接口?

我是一名学习 C++ 的 Java 程序员,我想知道 C++ 中是否有类似 Java 接口的东西,即另一个类可以实现/扩展多个类的类。谢谢。ps 新来的,如果我做错了什么,请告诉我。

4

2 回答 2

32

在 C++ 中,仅包含纯虚方法的类表示接口。

例子:

// Define the Serializable interface.
class Serializable {
     // virtual destructor is required if the object may
     // be deleted through a pointer to Serializable
    virtual ~Serializable() {}

    virtual std::string serialize() const = 0;
};

// Implements the Serializable interface
class MyClass : public MyBaseClass, public virtual Serializable {
    virtual std::string serialize() const { 
        // Implementation goes here.
    }
};
于 2012-08-14T04:58:16.323 回答
-5

要模拟 Java interface,您可以使用仅具有纯虚函数的普通基础。

您需要使用虚拟继承,否则您可能会得到重复继承:同一个类可以在 C++ 中多次成为基类。这意味着在这种情况下,对该基类的访问将是模棱两可的。

C++没有提供与 Java 完全等价的interface功能:在 C++ 中,重写虚函数只能在具有虚函数声明的类的派生类中完成,而在 Java 中,interface可以在 a 中声明方法的重写器基类。

[例子:

struct B1 {
    void foo ();
};

struct B2 {
    virtual void foo () = 0;
};

struct D : B1, B2 {
    // no declaration of foo() here
};

D也继承了函数声明:B1::foo()B2::foo().

B2::foo()是纯虚拟的,D::B2::foo()也是如此;B1::foo()不会覆盖B2::foo(),因为B2它不是B1.

因此,D是一个抽象类。

--结束示例]

无论如何,您为什么要在 C++ 中模拟 Java 的任意限制?

编辑:添加示例以进行说明。

于 2012-08-14T06:06:30.187 回答