长路漫漫

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

《Itanium C++ ABI》文档2.3节中描述:

A pointer to data member is an offset from the base address of the class object containing it, represented as a ptrdiff_t. It has the size and alignment attributes of a ptrdiff_t. A NULL pointer is represented as -1.

测试一:

// test.cpp
#include <iostream>
#define PRINT(var) do { std::cout << (var) << std::endl; } while(0)

class CTest
{
public:
    int a;
    int b;
};

int main()
{
    int CTest::*p0 = 0;
    int CTest::*p1 = &CTest::a;
    int CTest::*p2 = &CTest::b;
    
    PRINT(*(long *)(&p0));
    PRINT(*(long *)(&p1));
    PRINT(*(long *)(&p2));

    return 0;
}

输出结果为:

-1
0
4

测试二:

// test.cpp
#include <iostream>
#define PRINT(var) do { std::cout << (var) << std::endl; } while(0)

class Base
{
public:
    int a;
    int b;
};

class Derived : public Base
{
public:
    int c;
    int d;
};

int main()
{
    int Derived::*p1 = &Derived::a;
    int Derived::*p2 = &Derived::b;
    int Derived::*p3 = &Derived::c;
    int Derived::*p4 = &Derived::d;

    PRINT(*(long *)(&p1));
    PRINT(*(long *)(&p2));
    PRINT(*(long *)(&p3));
    PRINT(*(long *)(&p4));

    return 0;
}

输出结果为:

0
4
8
12

posted on 2012-08-27 13:31  opangle  阅读(340)  评论(0编辑  收藏  举报