我有这个代码(菱形继承(钻石问题)):
#include
sử dụng không gian tên 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 chính()
{
Bottom b;
b.Right::Top::print();
}
我想在 Đứng đầu
类中调用 print()
。
当我尝试编译它时,我收到错误:'Top' is an ambiguous base of 'Bottom'
on this line: b.Right::Top::print();
为什么会模棱两可?我明确指定我想要 Đứng đầu
từ Right
而不是来自 Bên trái
。
我不想知道怎么做,是的,它可以通过引用、虚拟继承等来完成。我只想知道为什么是 b.Right::Top::print();
模棱两可。
Why is it ambiguous? I explicitly specified that I want Đứng đầu
từ Right
and not from Bên trái
.
这是您的意图,但实际情况并非如此。 Right::Top::print()
显式命名您要调用的成员函数,即&Top::print
。但它没有指定我们在 b
的哪个子对象上调用该成员函数。您的代码在概念上等同于:
auto print = &Bottom::Right::Top::print; // ok
(b.*print)(); // error
选择 in
的部分是明确的。从 b
đến Đứng đầu
的隐式转换是模棱两可的。您必须通过执行以下操作来明确区分您要进入的方向:
static_cast(b).Top::print();
Tôi là một lập trình viên xuất sắc, rất giỏi!