通过使用范围解析避免多重继承引起的歧义 [英] Avoid multiple inheritance induced ambiguity by using scope resolution

查看:67
本文介绍了通过使用范围解析避免多重继承引起的歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是多重继承的一个例子.我使用范围解析运算符而不是虚拟类来解决歧义.

Here is an example of multiple inheritance. I used the scope resolution operator to resolve the ambiguity instead of a virtual class.

struct A 
{
    int i;
};

struct B : A
{};

struct C : A
{};

struct D: B, C 
{
    void f()
    {
        B::i = 10;
    }
    void g()
    {
        std::cout << B::i <<std::endl;
    }
};

int main() 
{
    D d1;
    d1.f();
    d1.g();
    return 0;
}

B::i格式正确吗?

推荐答案

B::i格式正确吗?

是的.最相关的参考是 [class.qual]/1 :

Yes, it is. The most pertinent reference is [class.qual]/1:

如果限定ID的嵌套名称说明符指定了一个类,则 在嵌套名称说明符中查找后指定的名称 类的范围,但以下情况除外. 名称 代表该类别的一名或多名成员,或该类别中的一名 基类.

If the nested-name-specifier of a qualified-id nominates a class, the name specified after the nested-name-specifier is looked up in the scope of the class, except for the cases listed below. The name shall represent one or more members of that class or of one of its base classes.

您可以指定i的名称,因为它是B的基础成员.可访问性仅在之后进行检查,在您的情况下,它是公开的.

Which specifies you can name i on account of it being a member of B's base. The accessibility is only checked afterwards, and in your case it's public.

[class.access.base]/5

...对成员的访问受以下类的影响: 成员被命名.该命名类是成员所在的类 查找并找到姓名...该地点可以访问成员m 如果在类N中命名,则为R,如果

... The access to a member is affected by the class in which the member is named. This naming class is the class in which the member name was looked up and found... A member m is accessible at the point R when named in class N if

  • 存在一个N的基类B,它在R处可访问,而m在B类中命名时可在R处访问.

这篇关于通过使用范围解析避免多重继承引起的歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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