Equivalent of Java interfaces in C++? [duplicate]

不羁的心 提交于 2019-12-03 19:48:02

问题


Possible Duplicate:
How do you declare an interface in C++?
Interface as in java in c++?

I am a Java programmer learning C++, and I was wondering if there is something like Java interfaces in C++, i.e. classes that another class can implement/extend more than one of. Thanks. p.s. New here so tell me if I did anything wrong.


回答1:


In C++ a class containing only pure virtual methods denotes an interface.

Example:

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



回答2:


To emulate Java interface, you can use an ordinary base with only pure virtual functions.

You need to use virtual inheritance, otherwise you could get repeated inheritance: the same class can be a base class more than once in C++. This means that access of this base class would be ambiguous in this case.

C++ does not provide the exact equivalent of Java interface: in C++, overriding a virtual function can only be done in a derived class of the class with the virtual function declaration, whereas in Java, the overrider for a method in an interface can be declared in a base class.

[EXAMPLE:

struct B1 {
    void foo ();
};

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

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

D inherits too function declarations: B1::foo() and B2::foo().

B2::foo() is pure virtual, so D::B2::foo() is too; B1::foo() doesn't override B2::foo() because B2 isn't a derived class of B1.

Thus, D is an abstract class.

--end example]

Anyway, why would you emulate the arbitrary limits of Java in C++?

EDIT: added example for clarification.



来源:https://stackoverflow.com/questions/11945993/equivalent-of-java-interfaces-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!