如果我不想用C++的多继承,如何实现类似java的实现接口语法来扩展类?
黄舟
黄舟 2017-04-17 11:51:15
0
5
539

C++的多继承很难理解,可是如果单继承又觉得以后无法扩展功能,object-c有protocol,C++没有。

那如何扩展类的功能呢?

谢谢!

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(5)
洪涛

If you want to implement protocol or Java interface in C++, there is no other way except multiple inheritance... If you are afraid of conflicts, you can use virtual inheritance.
List two less feasible approaches:

One is to use composition instead of inheritance.
Define the set of functions you want to implement as a class A, and then use this class A as a member of a target class B. Then write a set of public methods for class B. These methods will implement their functions by transposing the methods of class A.
But this cannot achieve functions like interface. The reason is obvious, class A and class B are not in the same class system.

The second is to use templates.
If a class implements a desired set of functions, we can provide a tag for this class. If there is a function that needs to use this set of functions, then we can check whether there is such a tag in the given template parameters. If there is no such a tag, the program will not be compiled.
But this is more complicated. Do you really decide to do this?

In fact, if you do not require the implementation to be protocol-like, you can consider using factory functions/objects. That is, a set of parameters are provided as parameters of the function/method to generate a set of subclasses with the same base class but different implementations of the base class methods. This way their methods can be called using base class pointers.

洪涛

The semantics of interfaces implemented by Java classes are virtual inheritance in C++. The purpose is to avoid the ambiguity of diamond inheritance.

刘奇

The design pattern in C++ generally uses inheritance + combination to implement your extension;
You can consider using an abstract class Abstraction first and inherit it with the business class RefinedAbstraction;
Then, according to your needs, put the interfaces you need to extend the function into your abstract class or business class in a combined form (generally defined as pointers):
Implementor: Implement class interface
ConcreteImplementor: Concrete implementation class

You will understand by referring to this picture of the bridge mode in "Illustrated Design Patterns":

For details, please visit:
http://design-patterns.readthedocs.org/zh_CN/latest/structural_patterns/bridge.html

Peter_Zhu

Use composition as much as possible and inheritance less, java, objC and C++ are all

洪涛

Use less inheritance and more std::function / std::bing / lambda

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template