一、栗子
1、源码
#include <iostream>
#include <stdio.h>
class Base
{
public:
Base() { std::cout << "Base 的 this 指针:" << this << std::endl; }
public:
int bi_;
};
class A : public Base
{
public:
A() { std::cout << "A 的 this 指针:" << this << std::endl; }
public:
virtual void func() {};
public:
int i_;
};
int main()
{
A a;
std::cout << "A 的大小 = " << sizeof(A) << std::endl;
printf("A::bi_ = %d\n", &A::bi_);
printf("A::i_ = %d\n", &A::i_);
a.bi_ = 1;
a.i_ = 2;
return 0;
}
2、结果
Base 的 this 指针:004FF9B4
A 的 this 指针:004FF9B0
A 的大小 = 12
A::bi_ = 0
A::i_ = 8
二、分析
看上述代码的执行结果,发现了很有意思的事情:对象 a 中的父类和子类的 this 指针的值是不一样的。根据之前的分析结果,我们可以知道对象 a 的内存布局如下:
同时,代码的运行结果中显示,bi_ 变量的偏移地址为0,所以我们可以推测,该偏移地址是相对于类 Base 的 this 指针的。而 i_ 偏移地址为8,其是相对于类 A 的。
综上所述,对象访问成员变量的方法如下:
-
调整 this 指针。
-
计算成员变量首地址的偏移值。
注意,上述的操作均是由编译器完成!
(SAW:Game Over!)