Solve the function of functionality in multiple inheritance

zhaozj2021-02-16  66

When there is the same function declare name in the two interfaces, for example, Interface IA {Virtual Void Fun () = 0;}; interface ib {virtual void fun () = 0;

Class CD inherited these two interfaces: Class CD: Public Ia, Public IB {public: void fun ();

If this effect is to be achieved: there is a different implementation for the interface function FUN of IA and IB, which involves the problem of multiple inheritance functions.

Classic solution is the introduction middle class proposed in ARM: Class IAIMPL: Public IA {public: Virtual Void Fun () {internalFuna ();

Virtual void infrinkler () = 0;

Class ibimpl: public ip {public: Virtual void fun () {internalfunb ();

Virtual void infrinklefunb () = 0;

The current Class CD should be this Class CD: Public IAIMPL, PUBLIC IBIMPL {public: void infuna () {// Here IA :: Fun ()} void infunb () {// Implement IB :: fun () }};

In this way, the same name function problem with multiple inheritance is successfully solved, where the FUN function in IAIMPL and IBIMPL uses the simplest template method mode.

Of course, this is used here, which can be replaced with a template. The more efficient solution is as follows: Template Class IAIMPL: Public IA {public: Virtual void fun () {t * pt = static_cast (this); PT-> InternalFuna ();}};

Template Class IbiMPL: Public IB {PUBLIC: Virtual Void Fun () {T * Pt = Static_cast (this); PT-> InternalFunb ();}};

Class CD: Public IAIMPL , Public IbiMPL {Public: Void InternalFuna () {// Here IA :: Fun ()} Void InternalFunb () {// Here Ib :: Fun ()}} ;

This avoids the overhead of the virtual function call.

转载请注明原文地址:https://www.9cbs.com/read-17486.html

New Post(0)