从子子类或孙子访问Base类

时间:2017-08-22 14:51:51

标签: c++ class inheritance base-class

我只是想直截了当,因为在我学习继承时,我注意到我可以从已经派生的类继承,并且从最派生的类直接访问Base类的成员。我认为以下显示了我的意思:

#include <iostream>

struct Base
{
    int member = 0;     // All members null
};

struct D1 : Base {};
struct D2 : Base {};
struct D3 : Base {};
struct D4 : Base {};

struct MostDerived : D1, D2, D3, D4 {};  // I know MostDerived now has 4 copies of Base


int main()
{
    MostDerived mostderived{};
    mostderived.D2::member = 2;                     // D2::Base::member = 2
    mostderived.D3::member = 3;                     // D3::Base::member = 3
    mostderived.D4::member = 4;                     // D4::Base::member = 4

    std::cout << mostderived.D1::member << '\n';        // Haven't touched D1, is still zero
    std::cout << mostderived.D1::Base::member << '\n';  // Equals 0, equivalent to above line
    std::cout << mostderived.Base::member << '\n';      // Read Base scope directly from most derived, equals zero

    mostderived.Base::member++;                         // Assign to member in Base scope directly from mostderived
                                                        // it now equals 1

    std::cout << mostderived.D1::member << '\n';        // But also does D1::member equal 1

    return 0;
}

通过mostderived.Base::member++,我改变了mostderived.D1::member的值。我只是想知道访问Base是否有意义,以及为什么它特别改变了D1的成员副本。我正在描绘布局的方式是MostDerived包含D1D2D3D4,每个都包含Base },所以它看起来如下。

enter image description here

1 个答案:

答案 0 :(得分:1)

  

所以通过做mostririved.Base :: member ++我改变了它的值   mostderived.D1 ::构件。

如果'MostDerived'继承自D1-4,那么

mostderived.Base::member++;
                  ^

含糊不清。

Becouse'MostDerived'具有此层次结构

int Base::member
int Base::member
int Base::member
int Base::member

Base可以替换为D1-4中的任何一个。

如果您要使用虚拟继承

struct D1 : virtual Base {};
struct D2 : virtual Base {};
struct D3 : virtual Base {};
struct D4 : virtual Base {};

这会导致'MostDerived'只包含一个基类,所以它不再是模棱两可的了

mostderived.Base::member++;

可以通过所有D1-4

访问此member
mostderived.D1::member = 1;
mostderived.D4::member = 4;

当然,由于所有D共享相同的变量,它将具有相同的值,例如:

MostDerived mostderived{};
mostderived.Base::member = 1;
std::cout << mostderived.D1::member << mostderived.D2::member << mostderived.D3::member << mostderived.D4::member;

将打印1111