使用多重继承时,为什么这个限定名有歧义? [英] When using multiple inheritance, why is this qualified name ambiguous?

查看:83
本文介绍了使用多重继承时,为什么这个限定名有歧义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Bottom 对象访问结构 Top 中的成员变量 x.

I'm trying to access the member variable x in struct Top using a Bottom object.

代码如下:

#include <cstdio>

struct Top
{
public:
    int x = 1;
};

struct Left : public Top
{
    int x = 2;
};

struct Right : public Top
{
    int x = 3;
};

struct Bottom : public Left, public Right
{
    int x = 4;
}; 

int main()
{
    Bottom b;
    std::printf("value: %d\n", b.Left::Top::x);
    return 0;
}

使用 gcc 4.8 会出现以下错误:

This gives the following error using gcc 4.8:

main.cpp: In function 'int main()':
main.cpp:27:45: error: 'Top' is an ambiguous base of 'Bottom'
std::printf("value: %d\n", b.Left::Top::x);
                                        ^

这是如何模棱两可的,我如何使用限定名称访问它?

How is this ambiguous and how do I access it with a qualified name?

推荐答案

问题是C++没有办法直接表达多级"类成员的概念,比如成员xLeftTop 子对象的 code>".Left::Top::x 的意思是Left::Top 表示的类型中的成员 x" - 以及表示的类型by Left::Top 就是 Top.

The problem is that C++ has no way to directly express the concept of "multiple-level" class members, such as "the member x of the Top subobject of Left". What Left::Top::x means is "the member x in the type denoted by Left::Top" - and the type denoted by Left::Top is exactly Top.

这就是为什么你可以写一些奇怪的东西

This is why you can write odd things like

int Left::* ptr = &Right::Top::x;

因为 = 的右侧完全等同于 &Top::x,并且指向基类成员的指针是隐式可转换的指向派生类成员的指针.(这种转换的结果仍然是指派生类的基类子对象中的成员.)

because the right hand side of the = is exactly equivalent to &Top::x, and a pointer-to-base-class-member is implicitly convertible to a pointer-to-derived-class-member. (The result of this conversion still refers to the member in the base-class subobject of the derived class.)

要消除歧义,您可以按照 static_cast<Left &>(b).Top::x 或使用指向成员的指针 - 给定 int Left::* ptr = &Top::x;, b.*ptr 将引用 Top 中的 xbLeft子对象的code>子对象.

To disambiguate, you can either do something along the lines of static_cast<Left &>(b).Top::x or use a pointer-to-member - given int Left::* ptr = &Top::x;, b.*ptr will refer to the x in the Top subobject of the Left subobject of b.

这篇关于使用多重继承时,为什么这个限定名有歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆