访问模棱两可的班级成员

时间:2011-08-12 23:29:52

标签: c++

我有一颗钻石。我想访问类成员。我正在使用mingw 问题如何在不重新声明类的情况下访问成员“top :: A”

#include <cstdio>
class top {
public:
    const char A;
    top(): A('t') {}
};
class left: public top {
public:
    const char A;
    left():A('l'){}
};
class right: public top {};
class bottom: public left, public right {};

int main() {
    bottom obj;
    printf("%c\n", obj.bottom::right::A); //using right::A, inherited from top::A
    printf("%c\n", obj.bottom::left::A); //using left::A and left::top::A is hidden
    //printf("%c\n", obj.bottom::left::top::A); //error. How to access it?
    return 0;
}

当我删除评论mingw给我一个错误:

'top' is an ambiguous base of 'bottom'  

更新:看起来像投射类型有效:

printf("%c\n", static_cast<top>(static_cast<left>(obj)).A);
printf("%c\n", static_cast<left>(obj).::top::A);
printf("%c\n", reinterpret_cast<top&>(obj).A);//considered bad
printf("%c\n", (reinterpret_cast<top*>(&obj))->A);//considered evil
//      printf("%c\n", static_cast<top&>(obj).A);//error

3 个答案:

答案 0 :(得分:4)

如果不进行虚拟继承,可以按一下类型来说服编译器选择正确的基类:

printf("%c\n", static_cast<left&>(obj).::top::A);

答案 1 :(得分:2)

我不是一个C ++专家,但可能不会做以下工作?

left &asLeft = obj ;
top &asTop = asLeft ;
cout << asTop.A << endl ;

答案 2 :(得分:-1)