c ++指向成员的指针(指向成员基类的指针)

时间:2017-10-12 14:32:25

标签: c++ pointers pointer-to-member

class Base { int type; };
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
class Container
{
public:
    Derived1 f1;
    Derived2 f2;
};

Container c;

size_t offset = (size_t) static_cast<Base*>( &reinterpret_cast<Container*>(0)->f2 );
Base* base = reinterpret_cast<Base*>( (size_t) c + offset ); // ok

Base Container::* ptr = &Container::f2; // compile error!
base = c.*ptr;

使用指向成员的指针获取指向Base的指针的任何有效方法是什么?

1 个答案:

答案 0 :(得分:0)

您很可能正在寻找抵消和所有相关工作人员 How to calculate offset of a class member at compile time?