简体   繁体   English

数据成员访问歧义和菱形继承

[英]Data member access ambiguity and diamond inheritance

Given the code:鉴于代码:

#include <cassert>
#include <cstdlib>

int
main()
{
    struct A { int i; A(int j) : i(j) { ; } };
    struct E { int i = 3; };
    struct B : A, E { using A::A; };
    struct C : A, E { using A::A; };
    struct D : B, C { D(int i, int j) : B{i}, C{j} { ; } };
    D d{1, 2};
    assert(d.B::A::i == 1);
    assert(d.C::A::i == 2);
    assert(d.B::E::i == 3);
    assert(d.C::E::i == 3);
    return EXIT_SUCCESS;
}

There are two diamond inheritance occurrences.有两个钻石继承事件。 I want to access to specified data members i in all bases.我想访问所有基地中的指定数据成员i How to gain the access?如何获得访问权限? The code from example produces an error:示例中的代码产生错误:

main.cpp:13:12: error: ambiguous conversion from derived class 'D' to base class 'A':
    struct D -> struct B -> struct A
    struct D -> struct C -> struct A
    assert(d.B::A::i == 1);
           ^
/usr/include/assert.h:92:5: note: expanded from macro 'assert'
  ((expr)                                                               \
    ^
main.cpp:14:12: error: ambiguous conversion from derived class 'D' to base class 'A':
    struct D -> struct B -> struct A
    struct D -> struct C -> struct A
    assert(d.C::A::i == 2);
           ^
/usr/include/assert.h:92:5: note: expanded from macro 'assert'
  ((expr)                                                               \
    ^
main.cpp:15:12: error: ambiguous conversion from derived class 'D' to base class 'E':
    struct D -> struct B -> struct E
    struct D -> struct C -> struct E
    assert(d.B::E::i == 3);
           ^
/usr/include/assert.h:92:5: note: expanded from macro 'assert'
  ((expr)                                                               \
    ^
main.cpp:16:12: error: ambiguous conversion from derived class 'D' to base class 'E':
    struct D -> struct B -> struct E
    struct D -> struct C -> struct E
    assert(d.C::E::i == 3);
           ^
/usr/include/assert.h:92:5: note: expanded from macro 'assert'
  ((expr)                                                               \
    ^
4 errors generated.

Live example活生生的例子

Compiler is clang 3.7.0 .编译器是clang 3.7.0

That is a rather messy class hierarchy.这是一个相当混乱的类层次结构。 I hope you don't intend to use it in a real application.我希望您不打算在实际应用程序中使用它。

Here's one way to get around the hurdle:这是绕过障碍的一种方法:

// Get references to the B and C parts of D.
B& b = d;
C& c = d;

// Now you can get the A::i and the E::i.
assert(b.A::i == 1);
assert(c.A::i == 2);
assert(b.E::i == 3);
assert(c.E::i == 3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM