我有这段代码(菱形继承(钻石问题)):
#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();
}
我想在 Top
类中调用 print()
。
当我尝试编译它时出现错误:'Top' is an ambiguous base of 'Bottom'
在这一行:b.Right::Top::print();
为什么会模棱两可?我明确指定我想要 Right
的 Top
而不是 Left
。
我不想知道怎么做,是的,它可以通过引用、虚拟继承等来完成。我只想知道为什么 b.Right::Top::print();
模棱两可。
最佳答案
Why is it ambiguous? I explicitly specified that I want
Top
fromRight
and not fromLeft
.
那是您的意图,但实际情况并非如此。 Right::Top::print()
显式命名要调用的成员函数,即 &Top::print
。但它没有指定我们在 b
的哪个子对象上调用该成员函数。您的代码在概念上等同于:
auto print = &Bottom::Right::Top::print; // ok
(b.*print)(); // error
选择print
的部分是明确的。这是从 b
到 Top
的隐式转换,这是不明确的。您必须通过执行类似以下操作来明确消除前进方向的歧义:
static_cast<Right&>(b).Top::print();
关于c++ - 死亡钻石和作用域解析运算符 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42439980/