关于内存偏移量

[复制链接]
1973|5
 楼主| baidudz 发表于 2013-10-30 18:49 | 显示全部楼层 |阅读模式
在程序员面试宝典上有这么一道题:

#include <string.h>
#include <iostream.h>
#include <stdio.h>

class A
{
public:
A(){m_a = 1; m_b = 2;}
~A(){};
void fun(){printf("%d%d",m_a,m_b);}
public:
int m_a;
int m_b;
};

class B
{
public:
B(){m_c = 3;}
~B();
void fun(){printf("%d",m_c);}
public:
int m_c;
};

int tmain(void)
{
        A a;
        B *pb = (B*)(&a);
        cout << &a << endl;            //0x22ff58
        cout << &(a.m_a) << endl;      //print the address of the a.m_a 0x22ff58
printf("%p\n",&A::m_a);        //print the offset from m_a to the beginning A object
                                       //address 00000000
printf("%p\n",&A::m_b);        //print the offset from m_a to the beginning A object
                                       //address 00000004
printf("%p\n",&B::m_cn);       //print the offset from m_c to the beginning B object
                                       //address 00000000
system("PAUSE");
return 0;
}

我的问题是:
(1)为什么内存的偏移是从成员变量开始?成员函数放在哪了呢?比如printf("%p\n",&A::fun);输出的是个
很大的偏移量,为什么?
(2)类在内存中具体是怎么保存的?
火箭球迷 发表于 2013-10-30 19:00 | 显示全部楼层
如果没有虚函数, class的内存和c中的struct一样的, 成员函数只是给编译器看的, 在空间上和普通函数没什么区别.
如果有虚函数, 在class的开头会多一个虚表指针, 这个指针指向的区域保存着每一个虚成员函数的地址
hsbjb 发表于 2013-10-30 19:16 | 显示全部楼层
看下这两本书:《深度探索C++对象模型》
《C++反汇编与逆向分析技术揭秘》
无冕之王 发表于 2013-10-30 19:27 | 显示全部楼层
火箭球迷 发表于 2013-10-30 19:00
如果没有虚函数, class的内存和c中的struct一样的, 成员函数只是给编译器看的, 在空间上和普通函数没什么区 ...

分析的很对
xsgy123 发表于 2013-10-31 16:50 | 显示全部楼层
题目难度不小
vivilzb1985 发表于 2013-11-4 23:23 | 显示全部楼层
这个有些难度的啊,我看看的啦
您需要登录后才可以回帖 登录 | 注册

本版积分规则

239

主题

2284

帖子

0

粉丝
快速回复 在线客服 返回列表 返回顶部
0