C++钻石继承

问题描述 投票:0回答:0

我认为这是一个愚蠢的问题,但也许有人可以帮助我。 为什么代码会导致错误:“a”是“d”的不明确基数? 由于不清楚我们需要从 d 到 a 的方式,这种感觉。 但还不够具体。

#include <iostream>

/*
     a
    |\
   |  \
  |    \
 b      c
  \    |
   \  |
    \|
    d
*/

struct a 
{
    virtual char const* name() const 
    {
        return "a";
    }
};

struct b : a {
    char const* name() const
    {
        return "b";
    }
};

struct c : a {
    char const* name() const
    {
        return "c";
    }
};

struct d : b, c
{
    char const* name() const
    {
        return "d";
    }
};

int main()
{
    d dd;
    a const& aa = dd; // why this row causes error: ‘a’ is an ambiguous base of ‘d’
    
    // try {
    //     throw d();
    // }
    // catch (a const &e) {
    //     std::cout << "error: " << e.name() << '\n';
    // }
    return 0;
}
c++ inheritance multiple-inheritance diamond-problem
© www.soinside.com 2019 - 2024. All rights reserved.