zoukankan      html  css  js  c++  java
  • 指向类的成员变量的指针

    《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

  • 相关阅读:
    Airflow使用笔记
    公共关系学(第二版)笔记
    公众关系秘籍
    SQL SERVER XML 学习总结
    hadoop 1.2.1 配置
    ssh
    centos&windows的共享文件(通过挂载)
    代理设置(wget/yum)
    环境变量设置
    centos7 自定义服务
  • 原文地址:https://www.cnblogs.com/opangle/p/2658418.html
Copyright © 2011-2022 走看看