分享

成员函数指针

 MyBear 2013-07-23
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54


#pragma once

#include <iostream>

class CPoint {
public:
    float x;
    float y;
    float z;
};

/*
 * @Func : 测试成员变量指针的偏移,包括(1)偏移值是否+1;(2)空成员指针的偏移是多少
 *
 * @测试方法:(1) 输出偏移值;(2) 观察空成员指针与指向首个成员变量指针的值及地址
 *
 * @测试结果及分析
 * (1) 输出结果
             &CPoint::x = 00000000
             &CPoint::y = 00000004
             &CPoint::z = 00000008
             x : 1
             y : 1
             z : 1
 * 从输出结果可以看出,偏移量并没有增加1,因此可能是VC做了特殊处理。另外使用cout不能得到正确的结果。
 * (2) 输出结果
            float CPoint::*p1 = 0; 其中p1的地址为0xffffffff,内存值不能读取
            float CPoint::*p2 = &CPoint::x; 其中p2的地址为0x00000000,内存值不能读取
 * 从输出结果可以看出,VC使得这两种指针不同
 *
 * @说明:(1) 在VC中,偏移量没有额外+1;(2) 在VC中,通过置两种指针的地址为不同的值,从而进行区别
 */

void Test_Point2DM(){
    CPoint org;
    float CPoint::*p1 = 0;
    float CPoint::*p2 = &CPoint::x;

    if (p1 == p2){
        std::cout << " p1 & p2 contain the same value -- ";
        std::cout << " they must address the same member! " << std::endl;
    }

    printf("&CPoint:: = %p\n", p1);
    printf("&CPoint::x = %p\n", &CPoint::x);
    printf("&CPoint::y = %p\n", &CPoint::y);
    printf("&CPoint::z = %p\n", &CPoint::z);

    std::cout << "x : " << &CPoint::x << std::endl; // 使用这种方式输出的值不对
    std::cout << "y : " << &CPoint::y << std::endl;
    std::cout << "z : " << &CPoint::z << std::endl;

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多