我只想弄清楚一点,因为当我学习继承时,我注意到我可以从一个已经派生的类继承,并且可以从大多数派生的类直接访问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,因此如下所示。

c&#43;&#43; - 从子子类或孙子类访问基类-LMLPHP

最佳答案

因此,通过执行mostderived.Base :: member ++,我更改了
  D1 :: member。


如果“ MostDerived”继承自D1-4,则

mostderived.Base::member++;
                  ^


是am昧的。

因为“ 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共享同一个变量,因此对于所有D,它都具有相同的值,例如:

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


将打印1111

09-06 16:40