加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 多重继承模糊基类

发布时间:2020-12-16 03:11:30 所属栏目:百科 来源:网络整理
导读:考虑代码 struct Base{};struct Derived: public Base{};struct A: public Base{};struct B: public A,public Base{};struct C: public A,public Derived{}; // why no ambiguity here?int main() {} 编译器(g 5.1)警告 warning: direct base 'Base' inacces
考虑代码
struct Base{};
struct Derived: public Base{};

struct A: public Base{};

struct B: public A,public Base{};

struct C: public A,public Derived{}; // why no ambiguity here?

int main() {}

编译器(g 5.1)警告

warning: direct base 'Base' inaccessible in 'B' due to ambiguity struct B: public A,public Base{};

我明白这一点,基地在B.

>为什么C没有警告? C和C都不继承,它们都继承自Base?
>为什么添加虚拟

struct Derived: virtual Base{};

结果现在B和C发出警告,生活在Wandbox

warning: direct base 'Base' inaccessible in 'B' due to ambiguity struct B: public A,public Base{};

warning: direct base 'Base' inaccessible in 'C' due to ambiguity struct C: public A,public Derived{};

解决方法

在B中,不可能直接引用继承的Base子对象的成员.考虑:
struct Base {
    int x;
};

struct B: public A,public Base {
    void foo() {
        int& x1 = A::x; // OK
        int& x2 = x; // ambiguous
        // no way to refer to the x in the direct base
    }
};

在C这不是一个问题.可以使用限定名称来引用这两个x:

struct C: public A,public Derived {
    void foo() {
        int& x1 = A::x; // OK
        int& x2 = Derived::x; // OK
    }
};

所以你得到的警告是一个直接的基地也是通过另一个路径继承的唯一有用的.

对于你的第二个问题,我无法用g -5.1重现Coliru上的C的警告.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读