ATL布幔之下的秘密(2)
2006-07-22 22:55:03 来源:WEB开发网那么现在,让我邀请纯虚函数来加入这一游戏,再来看看它的行为吧。请看以下的程序:
程序27. #include <iostream>
在debug和release模式下,程序的输出有所不同。下面是debug模式的输出:
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 1st entry = " << (int*)*((int*)*(int*)this+0) << endl;
cout << "Value at Vtable 2nd entry = " << (int*)*((int*)*(int*)this+1) << endl;
cout << endl;
}
virtual void f1() = 0;
virtual void f2() = 0;
};
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 1st entry = " << (int*)*((int*)*(int*)this+0) << endl;
cout << "Value at Vtable 2nd entry = " << (int*)*((int*)*(int*)this+1) << endl;
cout << endl;
}
virtual void f1() { cout << "Drive::f1" << endl; }
virtual void f2() { cout << "Drive::f2" << endl; }
};
int main() {
Drive d;
return 0;
}In Base
以下则是release模式的输出:
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C0BC
Value at Vtable 1st entry = 00420CB0
Value at Vtable 2nd entry = 00420CB0
In Drive
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C0A4
Value at Vtable 1st entry = 00401212
Value at Vtable 2nd entry = 0040128FIn Base
为了更好地弄懂这一原理,我们需要对程序作少许的改动,并尝试使用函数指针来调用虚函数。
Virtual Pointer = 0012FF80
Address of Vtable = 0042115C
Value at Vtable 1st entry = 0041245D
Value at Vtable 2nd entry = 0041245D
In Drive
Virtual Pointer = 0012FF80
Address of Vtable = 00421154
Value at Vtable 1st entry = 00401310
Value at Vtable 2nd entry = 00401380
更多精彩
赞助商链接