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

2019-04-04 10:36发布

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.

2条回答
Viruses.
2楼-- · 2019-04-04 11:07

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.
    }
};
查看更多
趁早两清
3楼-- · 2019-04-04 11:11

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.

查看更多
登录 后发表回答