C + + is allowed multiple inheritance, and this design is both problematic and not very common, so both Java and C # adopt another approach: interface (Interface). The class inheritance (Implementation) interface does not indicate the is-a relationship, but rather "has a certain function", "conforms to a certain nature" relationship. C + + Although the syntax does not support the interface, but this idea can be used to use it. Like designing an interface like this:
struct hashable{ virtual0;};
Then let a class inherit it, and implement the function, which means that the class is hash-able.
Things are not so simple, in C + +, the interface can also have a lot of magic usage, especially when confronted with generics. Sometimes, when you inherit an interface and implement a function, it will automatically help you implement other functions; Sometimes, when you inherit, everything is done. Take a look at the following example (from Boost::operators):
template<classT>structless_than_comparable{friendBOOL operator> (Const&t x,Const&t y) {return! (X<y | | x==y);} FriendBOOL operator<= (Const&t x,Const&t y) {returnX<y | | x==y;} FriendBOOL operator>= (Const&t x,Const&t y) {return! (x<y);}};
It's slightly strange to use, and it's necessary to use subclasses as template parameters for the parent class, such as:
class public less_than_comparable<my_class>{ // implement friend operator< and operator ==};
Unlike in Java or C #, the functions defined in an interface are not the same as those implemented in subclasses, and functions in an interface are functions that extend the implementation function. In this way, the programmer can automatically obtain >, <= and >= implementations as long as the < and = = are implemented.
If the function in a generic interface like this is not related to the type, and does not depend on other functions, it can achieve the "inheritance is realized" effect, an example is Boost::serialization::singleton, this in the online about the implementation of the single-piece mode can be seen in the article.
Interfaces in C + + (Interface)