#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "In Base" << endl;
cout << "Virtual Pointer = " << (int*)this << endl;
cout << "Address of Vtable = "
<< (int*)*(int*)this << endl;
cout << "Value at Vtable = "
<< (int*)*(int*)*(int*)this << endl;
cout << endl;
}
virtual void f1() { cout << "Base::f1" << endl; }
};
class Drive : public Base {
public:
Drive() {
cout << "In Drive" << endl;
cout << "Virtual Pointer = "
<< (int*)this << endl;
cout << "Address of Vtable = "
<< (int*)*(int*)this << endl;
cout << "Value at Vtable = "
<< (int*)*(int*)*(int*)this << endl;
cout << endl;
}
virtual void f1() { cout << "Drive::f2" << endl; }
};
int main() {
Drive d;
return 0;
}
这个程序的输出是
In Base
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C08C
Value at Vtable = 004010F0
In Drive
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C07C
Value at Vtable = 00401217
按照代码,我可以看到,当我创建一个 Drive 对象时,Base 构造函数也运行并显示与 Drive 的虚拟指针相同的虚拟指针地址:0012FF7C。奇怪的是,当我在 Base 和 Drive 类的构造函数中取消引用该地址时,它指向不同的值,这意味着有两个 vtable,一个在 0046C08C,另一个在 0046C07C。当 1 指针指向 2 地址时,它在 Drive 对象的结构和 c 语言中都很难理解。