2

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

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; 

产生相同的值,如果继承树不是虚拟的,它们不应该是不同的偏移量吗?

4

1 回答 1

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
于 2012-05-06T05:41:58.633 回答