死亡钻石和范围解析算子(c ++)

PcA*_*cAF 13 c++ inheritance multiple-inheritance diamond-problem

我有这个代码(钻石问题):

#include <iostream>
using namespace std;

struct Top
{
    void print() { cout << "Top::print()" << endl; }
};

struct Right : Top 
{
    void print() { cout << "Right::print()" << endl; }
};

struct Left : Top 
{
    void print() { cout << "Left::print()" << endl; }
};

struct Bottom: Right, Left{};

int main()
{
    Bottom b;
    b.Right::Top::print();
}
Run Code Online (Sandbox Code Playgroud)

我想print()Top课堂上打电话.

当我尝试编译它时,我得到错误:'Top' is an ambiguous base of 'Bottom'在这一行:b.Right::Top::print(); 为什么它不明确?我明确规定,我想TopRight与不从Left.

我不想知道怎么做,是的,它可以通过引用,虚拟继承等来完成.我只是想知道为什么是b.Right::Top::print();模棱两可的.

Bar*_*rry 16

为什么它含糊不清?我明确规定,我想TopRight与不从Left.

这是你的意图,但事实并非如此.Right::Top::print()显式命名要调用的成员函数,即&Top::print.但它没有指定b我们在哪个子对象上调用该成员函数.您的代码在概念上等同于:

auto print = &Bottom::Right::Top::print;  // ok
(b.*print)();                             // error
Run Code Online (Sandbox Code Playgroud)

选择的部分print是明确的.这是从隐式转换bTop这是不明确的.你必须通过做类似的事情明确消除你进入的方向的歧义:

static_cast<Right&>(b).Top::print();
Run Code Online (Sandbox Code Playgroud)