对C ++中类成员的观点感到困惑

时间:2014-03-09 14:56:37

标签: c++ member-pointers

以下三个课程:

class Base
{
public:
    int var1;
};
class Base2
{
public:
    int var2;
};
class Derive:public Base,public Base2
{
public:
    int var3;
};
int main()
{

    printf("%d %d %d %d %d", &Base::var1, &Base2::var2, &Derive::var1, &Derive::var2, &Derive::var3);
    int Derive::* p = &Derive::var1;
    Derive d;
    d.var1 = 2;
    printf("%d", d.*p);
}

输出结果为0 0 0 0 8 2。我对&Derive::var1&Derive::var2的结果感到困惑。为什么他们分别是0而不是04

注意:我用gcc4.7.1和vs2010测试它。结果是一样的。

1 个答案:

答案 0 :(得分:0)

@HerbSutter在Address of C++ pointer to class data member in Visual Studio中回答:

&Derive::var1的类型为int Base::*而不是int Derive::*

&Derive::var2的类型为int Base2::*而不是int Derive::*