2010年6月19日星期六

取多重继承类中子类的偏移

当一个Class继承多个基类时,如何取其中各个基类相对偏移?

通过类型转换即可,如下例:


#include <stdio.h>

class CBase
{
public:
    int b;
    virtual void vbase() {}
    void base()
    {
        printf("CBase::this = 0x%p\n", this);
    }
};

class COther
{
public:
    int o1;
    int o2;
    virtual void vother() {}
    void other()
    {
        printf("CBase::this = 0x%p\n", this);
    }
};

class CDerive : public CBase, public COther
{
public:
    int d1;
    int d2;
    int d3;
    void derive()
    {
        printf("CBase::this = 0x%p\n", this);
    }
};

// Get the offset of member in class
#define GetOffsetOfMember(member, CClass) (((int) &((CClass *) 1)->member) - 1)

// Get the offset of sub class in derived class
#define GetOffsetOfClass(CBase, CSub) (((int) (static_cast <CBase *>((CSub *) 1))) - 1)


int main(int argn, char *argv[])
{
    printf("COther@CDerive = %d\n", GetOffsetOfClass(COther, CDerive));
    printf("o1@CDerive= %d\n", GetOffsetOfMember(o1, CDerive));
    printf("b@CDerive= %d\n", GetOffsetOfMember(b, CDerive));
}




需要注意的是,不要直接使用指针0进行转换取类指针偏移(这是计算类成员变量的常用方法)

没有评论:

发表评论