指向类的成员变量的指针

《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
原文链接: https://www.cnblogs.com/opangle/archive/2012/08/27/2658418.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/60964

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午9:43
下一篇 2023年2月9日 上午9:43

相关推荐