多态是C++面向对象程序设计的一个重要特性。以前看到虚函数觉得很神奇,为什么就能实现多态了呢。最初的时候曾设想,要实现运行时多态,应该让对象的某个部分始终指向一个固定的地址,子类继承的时候,就修改这个地址的内容。这样,父类和子类都是到同一个固定地址去读取内容,在运行时就能表现不同行为。
在看了《深度探索c++对象模型》之后,发现思路是类似的。在对象中,有一个指针指向一张虚函数表,里面按照次序存放了每一个虚函数,当子类继承的时候,即到虚函数表的指定位置去修改函数地址。当我们通过父类指针来操作一个子类的时候,调用虚函数,都是通过虚函数表+固定的偏移,这样运行期多态便实现了。
在深度《深度》这本书中,虚函数表大多放在了对象的末端,不知道现在的编译器是什么样的,因此本文就来实际做个实验测试一下。
实验环境:VC2013 Express
代码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class Parent {
public :
int parent;
Parent() : parent(10) {}
virtual void a() { cout << "Parent::a()" << endl; }
virtual void b() { cout << "Parent::b()" << endl; }
virtual void c() { cout << "Parent::c()" << endl; }
};
class Child : public Parent {
public :
int child;
Child() :child(100) {}
virtual void a() { cout << "Child::a()" << endl; }
virtual void b_child() { cout << "Child::b_child()" << endl; }
virtual void c_child() { cout << "Child::c_child()" << endl; }
};
class GrandChild : public Child{
public :
int grandchild;
GrandChild() :grandchild(1000) {}
virtual void a() { cout << "GrandChild::a()" << endl; }
virtual void b_child() { cout << "GrandChild::b_child()" << endl; }
virtual void c_grandchild() { cout << "GrandChild::c_grandchild()" << endl; }
};
int main()
{
typedef void (*func)();
GrandChild grandchild;
int **vtable = ( int **)&grandchild;
for ( int i = 0; (func)vtable[0][i] != nullptr; i++)
{
auto pfunc = (func)vtable[0][i];
cout << " [" <<i<< "] " ;
pfunc();
}
return 0;
}
|
相关文章
猜你喜欢
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 59
-
2025-05-29 34
-
2025-05-29 38
-
详解使用Mybatis-plus + velocity模板生成自定义的代码
2025-05-29 79 -
2025-05-29 54
热门评论