c++ - 数据成员访问歧义和菱形继承(钻石问题)

标签 c++ c++14 multiple-inheritance ambiguity name-lookup

给定代码:

#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;
}

有两个菱形继承(钻石问题)事件。我想访问所有库中的指定数据成员i。如何获得访问权限?示例中的代码产生错误:

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

编译器是clang 3.7.0

最佳答案

这是一个相当困惑的类层次结构。我希望您不打算在实际应用程序中使用它。

这是绕过这个障碍的一种方法:

// 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);

关于c++ - 数据成员访问歧义和菱形继承(钻石问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220947/

相关文章:

c++ - 如果某些类继承了抽象基类,则确定何时在某些类上使用函数

c++ - 当 CDialog.DoModal() 函数无法创建对话框时?

c++ - 找到第 10001 个素数时出错

c++ - 类内在线非静态字段初始化 + 对象池 -> 降低可维护性/可读性

c++ - 如何编写 Lambda 包装具有可选返回值的函数

c++ - 如何使用 MySQL Connector C++ 与数据库建立连接?

python - 没有 'consistent method resolution'错误的两级抽象类层次结构

c++ - 使用 enable_if 解决多重继承歧义

c++ - 扫描一个字符串,(在发布和 Debug模式下产生不同的值)

c++ - 通过初始化列表中的模板类构造函数调用非模板基类的构造函数