c++ - 为什么通过派生类使用 :: -operator 对基类的引用不明确?
问题描述
所以我想知道为什么下面的菱形问题的代码片段无法编译。我知道这个问题通常是通过虚拟继承来解决的,我不是故意使用它的。该代码只是为了展示我关于编译器为何称其为模棱两可的问题:所以我在 struct Base 中声明了两个成员变量,因为这两个子类(在本例中为 struct)实际上没有继承,我将引用 Base每个派生结构中的成员。现在我有另一个结构 AllDer,它将在两次知道 id_ 和 name_ 的问题中运行。但是,当我从 Base 明确定位 id_ 和 name_ 时,我不明白为什么这会模棱两可,因为直接目标变量是通过 ::-operator 指定的。
cout << Der1::Base::id_ << Der1::Base::name_ << '\n';
有人能告诉我,为什么编译器会在这里遇到问题吗?(请原谅可能错误的技术术语)编译器错误消息说:“从派生类 'AllDer' 到基类的模糊转换”。在 QT Creator 中为 C++ 使用 MinGW 7.3.0 64 位。
编辑:由于这个问题似乎由编译器处理不同,请检查链接的问题。
#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?
}
};
解决方案
Der1::Base
并且Der2::Base
是同一个类并且AllDer
从它派生两次。当您选择的成员不是 fromBase
而是 from时,您的方法将编译Der1
:
struct AllDer : public Der1, public Der2
{
void readAllDer()
{
cout << Der1::id_ << Der1::name_ << '\n';
}
};
推荐阅读
- r - 如何使R脚本跳转到下一行?
- mysql - 在一个 SQL 查询中合并两个表中的两列,并使用表中的值作为列名
- typescript - Typescript:属性类型通配符
- android - “重新启动接收器”无法正常工作 android [Xamarin.Android]
- javascript - 设置值属性时无法在文本区域中输入文本 - React
- python-3.x - 带循环的假值
- asp.net - 使用 asp.net websrevices (.asmx) 时是否需要特定权限才能访问特定方法?
- sql - 使用 SQL Server 过程比较两个表并在另一个表中插入所有具有添加或删除状态的记录
- c# - 通过 fcm c# 向 android 应用程序发送通知时不会出现通知
- javascript - 通过 API 将视频文件从本地驱动器保存/上传到 Azure Blob 存储?