打印

关于内存偏移量

[复制链接]
1062|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一样的, 成员函数只是给编译器看的, 在空间上和普通函数没什么区 ...

分析的很对

使用特权

评论回复
5
xsgy123| | 2013-10-31 16:50 | 只看该作者
题目难度不小

使用特权

评论回复
6
vivilzb1985| | 2013-11-4 23:23 | 只看该作者
这个有些难度的啊,我看看的啦

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

239

主题

2284

帖子

0

粉丝