可能重复:
你如何申报在C ++的接口?
接口如在C ++中的java?
我是一个Java程序员学习C ++,我想知道是否有类似的东西在C ++ Java接口,另一个类可以实现/延长超过一个,即类。 谢谢。 PS新这里,所以告诉我,如果我做错了什么。
可能重复:
你如何申报在C ++的接口?
接口如在C ++中的java?
我是一个Java程序员学习C ++,我想知道是否有类似的东西在C ++ Java接口,另一个类可以实现/延长超过一个,即类。 谢谢。 PS新这里,所以告诉我,如果我做错了什么。
在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.
}
};
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.