ATL布幔之下的秘密(2)
2006-07-22 22:55:03 来源:WEB开发网程序22.#include <iostream>
程序的输出为:
using namespace std;
class Base {
public:
Base() {
cout << "In Base" << endl;
cout << "This Pointer = " << (int*)this << endl;
cout << endl;
}
virtual void f() { cout << "Base::f" << endl; }
};
class Drive : public Base {
public:
Drive() {
cout << "In Drive" << endl;
cout << "This Pointer = " << (int*)this << endl;
cout << endl;
}
virtual void f() { cout << "Drive::f" << endl; }
};
int main() {
Drive d;
cout << "In Main" << endl;
cout << (int*)&d << endl;
return 0;
}In Base
这就表示,整个内存位置中,只有一个对象的存在。那么就让我们把这个指针指向的值打印出来,也就是虚函数表的指针vptr指向的值,VTable的地址。
This Pointer = 0012FF7C
In Drive
This Pointer = 0012FF7C
In Main
0012FF7C
程序23. #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
这个程序示范了基类和派生类中不同的虚函数表地址。为了更好地弄懂这一问题,那就让我们把继承层次加深,并添加一个继承于Drive类的MostDrive类,然后构建一个它的对象。
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C08C
Value at Vtable = 004010F0
In Drive
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C07C
Value at Vtable = 00401217
更多精彩
赞助商链接