指向多重继承中的继承数据成员的指针

时间:2012-05-06 04:30:26

标签: c++ inheritance multiple-inheritance diamond-problem

我试图查看是否有办法从具有多重继承的类中获取指向数据成员的指针。有没有办法消除它们的歧义并仍能获得正确的偏移?

struct Foo
{
    int BarData;
};

struct FooBarBaseA : public Foo
{
    int DataA;
};

struct FooBarBaseB : public Foo
{
    int DataB;  
};

struct FooBar : public FooBarBaseA, public FooBarBaseB 
{

};

Bar FooBar::* p1 = &FooBar::FooBarNodeA::BarData; // should be 0?
Bar FooBar::* p2 = &FooBar::FooBarNodeB::BarData; // should be 4 or 8?

编辑: 我确实希望它们是2个独立的值,但两者都是

int FooBar::FooBarBaseA::Foo:: *p1 = &FooBar::FooBarBaseA::Foo::BarData; and 
int FooBar::FooBarBaseB::Foo:: *p2 = &FooBar::FooBarBaseB::Foo::BarData; 

如果继承树不是虚拟的,那么它们是否应该是不同的偏移值?

1 个答案:

答案 0 :(得分:2)

我相信这段代码可以展示您的目标:

#include <iostream>
#include <typeinfo>

using std::cerr;

struct Foo
{
    int BarData;
};

struct FooBarBaseA : public Foo
{
    int DataA;
};

struct FooBarBaseB : public Foo
{
    int DataB;
};

struct FooBar : public FooBarBaseA, public FooBarBaseB
{

};

int main(int argc,char **argv)
{
  int FooBar::* p1 = static_cast<int FooBarBaseA::*>(&Foo::BarData);
  int FooBar::* p2 = static_cast<int FooBarBaseB::*>(&Foo::BarData);
  FooBar foo;
  foo.FooBarBaseA::BarData = 1;
  foo.FooBarBaseB::BarData = 2;
  cerr << (foo.*p1) << "\n";
  cerr << (foo.*p2) << "\n";
  return 0;
}

输出:

1
2