Virtual inheritance

zhaozj2021-02-08  221

In class overload we generally use the following ways:

Class base {void echo () {printf ("echo from base");}};

Class Middle: Public Base {}

Class Child: public middle {}

It can be clearly seen that the overload process is base-> middle-> child. Such a structure can use the default overload mode.

Void main () {Child C; c.echo (); // correct.

But at some point, we need to separate several subclasses from the base class, and then multiple inheritances by subclasses, this time the method will be wrong.

such as:

Class base {void echo () {printf ("echo from base");}};

Class Middle1: Public Base {} class middle2: public base {}

Class Child: public middle1, middle2 {}

Void main () {Child C; c.echo (); // error. Function call is not clear.

This is because the system considers that Middle1 and Middle2 are two types of systems coming from different BASE classes (although the two base declarations are exactly the same), they cannot confirm the one when the ECHO calls the Base class.

The solution is to use "virtual inheritance".

As follows:

Class base {void echo () {printf ("echo from base");}};

Class Middle1: Virtual Public Base {} class middle2: Virtual public base {}

Class Child: public middle1, middle2 {}

Void main () {Child C; c.echo (); // correct. Function calls from the same base class.

The following illustration makes it possible to describe the difference between default inheritance and virtual inheritance.

Default inheritance:

Base base | | | | MID1 MID2 | | | CHILD

There are two types of systems that are wrong.

Virtual inheritance:

Base | | | MID1 MID2 | | | CHILD

Integrate the system using virtual inheritance.

If you learn experience, please point out.

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

New Post(0)