一:
#include <iostream>
using namespace std;
class Class {
public:
virtual void fun() { cout << "Class::fun" << endl; }
};
int main() {
Class objClass;
cout << "Address of virtual pointer " << (int*)(&objClass+0) << endl;
cout << "Value at virtual pointer " << (int*)*(int*)(&objClass+0) << endl;
return 0;
}
二:
#include <iostream>
using namespace std;
class Class {
public:
virtual void fun() { cout << "Class::fun" << endl; }
};
int main() {
Class objClass;
cout << "Address of virtual pointer " << (int*)(&objClass+0) << endl;
cout << "Value at virtual pointer " << *(int*)(&objClass+0) << endl;
return 0;
}
http://www.codeproject.com/atl/ATL_UnderTheHood_.asp
原文出自这里对吧!
(int*)*(int*)(&objClass+0),从右向左读,解释如下:
(&objClass+0)
取得虚表指针 VPTR(指向虚拟表首地址) 的地址。
(int*)(&objClass+0)
因为虚表指针占用一个 int 的长度,所以这里通过加 (int *) 把地址 cast 成整数指针的技巧得到 VPTR。
*(int*)(&objClass+0)
VPTR 指向一张虚拟表 VTABLE,VTABLE就相当于一个数组,每个元素保存的是类中定义的虚函数地址。
* 表示取 VPTR 所指对象的值,这样就得到了 VTABLE 中第一个虚函数得地址,因为它位于表的开头。
(int*)*(int*)(&objClass+0)
同样我们通过 (int *) cast到整数指针的小把戏得到指向该虚函数得指针。