设为首页 加入收藏

TOP

ATL布幔下的秘密之内部工作方式(四)
2012-11-04 15:06:29 来源: 作者: 【 】 浏览:911
Tags:ATL 秘密 内部 工作 方式
  程序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
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

  这个程序的输出示范了虚函数表的最后一个入口为NULL。就让我们来用已有的知识来调用虚函数吧:


  程序13.

#include <iostream>
using namespace std;

class Class {
virtual void f() { cout << "Class::f" << endl; }
virtual void g() { cout << "Class::g" << endl; }
};

typedef void(*Fun)(void);

int main() {
Class objClass;

Fun pFun = NULL;

// 调用第一个虚函数
pFun = (Fun)*((int*)*(int*)(&objClass+0)+0);
pFun();

// 调用第二个虚函数
pFun = (Fun)*((int*)*(int*)(&objClass+0)+1);
pFun();

return 0;
}

  程序的输出为:

Class::f
Class::g

  现在我们来看看多重继承的情况。先看一个多重继承最简单的情况:

  程序14.

#include <iostream>
using namespace std;

class Base1 {
public:
virtual void f() { }
};

class Base2 {
public:
virtual void f() { }
};

class Base3 {
public:
virtual void f() { }
};

class Drive : public Base1, public Base2, public Base3 {
};

int main() {
Drive objDrive;
cout << "Size is = " << sizeof(objDrive) << endl;
return 0;
}

  程序的输出为:Size is = 12

  这个程序示范了当你从多个基类继承一个类的时候,这个派生类就会拥有所有基类的虚函数表指针。


  那么,当派生类也有虚函数表指针的时候会发生什么事情呢?让我们看看下面的程序来弄懂关于带有虚函数的多重继承的概念吧。

首页 上一页 1 2 3 4 5 下一页 尾页 4/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇ATL布幔下的秘密之虚函数背后的东.. 下一篇InstallShield制作带ODBC的安装软..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: