c++ - 如何访问多个级别的重写元素?

标签 c++ scope multiple-inheritance

如何访问基类的基类的重写成员?

#include <iostream>
using namespace std;

class A {public: char x; A(){x='A';};};
class B1 : public A {public: char x; B1(){x='B';};};
class B2 : public A {public: char x; B2(){x='B';};};
class C : public B1, public B2 {public: char x; C(){x='C';};};

int main(){
    C c;
    cout << c.x << endl; // prints C

    cout << c.B1::x << endl; // prints B
    cout << ((B1&) c).x << endl; // prints B

    // cout << c.A::x << endl; // normally prints A but doesn't work here
    cout << ((A&) c).x << endl; // prints A
    return 0;
}

引用(或指针)方式是唯一的可能吗? 我尝试了 A::B::x 以链接作用域运算符,但这不起作用。 假设我想保留“双 A”,即不使继承虚拟化。

((B&) c).x 似乎是 c.B::x 的一个很好的“解决方法”,但在虚函数的情况下它们不相等,是吗?

最佳答案

您可以通过引用转换加上作用域运算符访问 A 的两个版本,如下所示:((B1&) c).A::x((B2&) c).A::x .

cout << ((A&) c).x << endl;在我的编译器上失败,因为编译器不知道您要对 A 的数据的哪个拷贝进行操作。

关于c++ - 如何访问多个级别的重写元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3482672/

相关文章:

c++ - 字符串转char*函数

php - 将Mysql查询结果放入类内的数组中

python - Python如何传递多重继承的__init__参数

python numpy array/dict 多重继承

c++ - 简单的文档切换器功能?

c++ - 将 N 种类型的参数包折叠成 N-1 对

c++ - 从成员类函数创建线程

scope - 从 jQuery 函数外部访问变量

javascript - 状态设置方法没有影响主对象 - ReactJS

javascript - JavaScript 中的多重继承