#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;
這個程序的輸出時基類和驅動器類具有相同的虛擬指針,但2虛函數表是
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。在Drive對象的結構中很難理解,並且在1個指針指向2地址時也很難理解。
非常感謝你 –
請注意,這種特殊的行爲可能會被優化。一個好的優化器可以看到在你的例子中沒有使用最初的'Base'vtable。初始的vtable需要從'Base :: Base'間接調用'Base :: f1',但是你沒有這樣做。 – MSalters