首页 > 解决方案 > 为什么通过派生类使用 :: -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? 
    }
};

标签: c++

解决方案


Der1::Base并且Der2::Base是同一个类并且AllDer从它派生两次。当您选择的成员不是 fromBase而是 from时,您的方法将编译Der1

struct AllDer : public Der1, public Der2
{

    void readAllDer()
    {
        cout << Der1::id_ << Der1::name_ << '\n'; 
    }
};

推荐阅读