3

我有以下继承虚拟类的代码,并以某种方式inh::P1编译为char. 谁能解释为什么编译器在这个例子中选择char了?谢谢!intinh::P1

#include <iostream>

class myClass {public: typedef int P1;};
class myClassdef : virtual public myClass {};
class myClass2 : virtual public myClass { public: typedef char P1;};
class inh :  public myClassdef, public myClass2 {};

int main()
{
    std::cout << sizeof(inh::P1) << std::endl;
    return 0;
}
4

2 回答 2

4
sizeof(inh::P1);

查找从最直接的级别向上进行,因此inh::P1指的P1是通过 继承的myClass2,这确实是,类型char。如果您需要在最顶层的基类中引用成员,请使用:

  sizeof(myClass::P1);

注意:

inh::P1          --->  Refers to immediate base member, i.e: myClass2::P1
myClass2::P1     --->  Refers to member in current class scope, i.e: myClass2::P1
myClassdef::P1   --->  Refers to immediate base member, i.e: myClass::P1
myClass::P1      --->  Refers to member in current class scope, i.e: myClass::P1
于 2013-03-19T05:48:43.287 回答
1

基本上在多重继承中,查找是在最近的级别上完成的,因此当您调用 inh::P1 时,会调用 myClass2 的 P1。因此,如果您想引用 myClass ,请显式调用它,如下所示:

sizeof(myClass::P1);
于 2013-03-19T05:53:31.503 回答