ATL布幔之下的秘密
2006-07-22 22:55:08 来源:WEB开发网那么,有一个问题很自然地出现了——编译器是如何知道虚函数表的长度的呢?答案是:虚函数表的最后一个入口为NULL。你可以把程序改一改来考虑这个问题。
程序12. #include <iostream>
程序的输出为:
using namespace std;
class Class {
virtual void f() { cout << "Class::f" << endl; }
virtual void g() { cout << "Class::g" << endl; }
};
int main() {
Class objClass;
cout << "Address of virtual pointer " << (int*)(&objClass+0) << endl;
cout << "Value at virtual pointer i.e. Address of virtual table "
<< (int*)*(int*)(&objClass+0) << endl;
cout << endl << "Information about VTable" << endl << endl;
cout << "Value at 1st entry of VTable "
<< (int*)*((int*)*(int*)(&objClass+0)+0) << endl;
cout << "Value at 2nd entry of VTable "
<< (int*)*((int*)*(int*)(&objClass+0)+1) << endl;
cout << "Value at 3rd entry of VTable "
<< (int*)*((int*)*(int*)(&objClass+0)+2) << endl;
cout << "Value at 4th entry of VTable "
<< (int*)*((int*)*(int*)(&objClass+0)+3) << endl;
return 0;
}Address of virtual pointer 0012FF7C
这个程序的输出示范了虚函数表的最后一个入口为NULL。就让我们来用已有的知识来调用虚函数吧:
Value at virtual pointer i.e. Address of virtual table 0046C134
Information about VTable
Value at 1st entry of VTable 0040100A
Value at 2nd entry of VTable 0040129E
Value at 3rd entry of VTable 00000000
Value at 4th entry of VTable 73616C43
更多精彩
赞助商链接