C++ virtual base class

警告
本文最后更新于 2023-04-01,文中内容可能已过时。

C++ 中,由于存在多重继承的结构,往往会导致第三层继承类会拷贝顶级父类的多个成员变量,这将导致调用成员函数时,编译器不知道需要调用哪个成员,进而引发编译错误。

多重继承

/post/2023-04-01-C++-virtual-base-class/multi-class.png

存在多个成员变量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <cmath>
#include <iostream>

class A
{
public:
    A() {}

    void echo()
    {
        std::cout << "a:" << a << std::endl;
    }

protected:
    int a {10};
};

class B: public A
{};

class C: public A
{};

class D: public B, public C
{};

int main()
{
    D d;
    d.echo();

    return 0;
}

/post/2023-04-01-C++-virtual-base-class/error1.png

virtual base class

我们需要把 class Bclass C 对于 class A 的继承申明为 virtual base class,使用对于基类 class A成员拷贝只有一份

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class A
{
public:
    A() {}

    void echo()
    {
        std::cout << "a:" << a << std::endl;
    }

protected:
    int a {10};
};

class B: public virtual A
{};

class C: public virtual A
{};

class D: public B, public C
{};

/post/2023-04-01-C++-virtual-base-class/ok1.png

Ref

  1. https://www.simplilearn.com/tutorials/cpp-tutorial/virtual-base-class-in-cpp

相关内容

william 支付宝支付宝
william 微信微信
0%