Pregunta

I'm trying to see if there was a way to get a pointer to a data member from a class which has multiple inheritance. Is there a way to disambiguate them and still get the correct offsets?

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?

edit: I do want them to be 2 independent values, but both

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

yeild the same value, should they not be different offsets if the inheritance tree isn't virtual?

¿Fue útil?

Solución

I believe this code demonstrates what you are looking for:

#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;
}

Output:

1
2
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top