大家进来看看这两个程序,有什么不同的 (wengang )[回贴]
抱歉。那边我连续回复超过三次。没法再回,发这里。
小睡一会发现一处讲错了,照成下面都不正确。头晕晕的。
(int*)*(int*)(&objClass+0),从右向左读,解释如下:
(&objClass+0)
取得虚表指针 VPTR 的地址。
(int*)(&objClass+0)
因为虚表指针占用一个 int 的长度,所以这里通过加 (int *) 把地址 cast 成指向 VPTR 的指针。
cout << "Address of virtual pointer " << (int*)(&objClass+0) << endl;
输出该指针的值,既 VPTR 的地址。
*(int*)(&objClass+0)
VPTR 指向一张虚拟表 VTABLE,VPTR 指针变量保存的是 VTABLE 的地址。
* 表示 dereference 。
因此对上面这个指针进行 deference,取得的是 VPTR 的值,记 VTABLE 的地址。
(int*)*(int*)(&objClass+0)
同样我们通过 (int *) cast到整数指针的小把戏得到指向 VTABLE 的指针。
cout << "Value at virtual pointer " << (int*)*(int*)(&objClass+0) << endl;
指向 VTABLE 的指针包含的值是 VTABLE 的地址, 所以 cout 得到 VTABLE 的地址,存在于 VTPTR 指针变量里。
*(int*)*(int*)(&objClass+0)
我们知道 VTABLE 类似数组,里保存的是虚函数的地址。对指向 VTABLE 的指针进行 * 操作,得到的就是首个虚函数的地址。
(int*)*(int*)*(int*)(&objClass+0)
再一次 (int *) cast,得到指向该虚函数的指针。
cout << "Value at first entry of virtual table "
<< (int*)*(int*)*(int*)(&objClass+0) << endl;
输出指针的值就是虚函数的地址,也就是表头第一个记录值。
快晕了!
总结,用 cast 感觉很不舒服。尽量少用。
对地址用一次 (int *) cast ,相当于得到指向该地址的指针。
cout 输出的是指针变量所包含的值。