【发布时间】:2020-04-28 09:01:31
【问题描述】:
所以我想知道为什么菱形问题的以下代码sn-p无法编译。 我知道这个问题通常是通过虚拟继承来解决的,我不是故意使用它的。该代码只是为了展示我关于编译器为何称其为模棱两可的问题: 所以我在 struct Base 中声明了两个成员变量,因为这两个子类(在这种情况下是结构)实际上没有继承,所以我将在每个派生结构中引用 Base 成员。现在我有另一个结构 AllDer,它会在两次知道 id_ 和 name_ 的问题中运行。 但是,当我从 Base 显式定位 id_ 和 name_ 时,我不明白为什么这会模棱两可,因为直接目标变量是通过 ::-operator 指定的。
cout << Der1::Base::id_ << Der1::Base::name_ << '\n';
谁能告诉我,为什么编译器会在这里遇到问题? (请原谅可能错误的技术术语) 编译器错误消息说:“从派生类 'AllDer' 到基类的模糊转换”。在 QT Creator 中使用 MinGW 7.3.0 64 位 C++。
编辑:由于编译器似乎以不同的方式处理此问题,请检查链接的问题。
#include <string>
#include <iostream>
using std::string; using std::cout;
struct Base
{
int id_;
string name_; //target members for readAllDer() in AllDer
void read()
{
cout << id_ << ' ' << name_ << '\n';
}
};
struct Der1 : public Base
{
//Der1 has own reference to id_, name_
void readDer1()
{
cout << id_ << name_ << '\n';
}
};
struct Der2 : public Base
{
//Der2 has own reference to id_, name_
void readDer2()
{
cout << id_ << name_ << '\n';
}
};
//
struct AllDer : public Der1, public Der2
{
void readAllDer()
{
cout << Der1::Base::id_ << Der1::Base::name_ << '\n'; // Why is this ambiguous?
}
};
【问题讨论】:
-
请在问题中包含确切的错误信息
-
没有
Base::,嗯。 -
在我的机器上工作,你能给我们展示一个用例吗?
-
@Michael OP 也错过了包含错误,但现在我也很好奇你没有得到错误的编译器
-
Microsoft CL (Visual Studio 2019) @idclev463035818
标签: c++