4000 虚函数的多态实现小解
2017-11-12 17:10
134 查看
要做批注的只有一点,虚表在这几个类中是共享的,并不是每一个类都生成一份自己的虚表。解析是,子类中覆盖的父类中的虚函数,在虚表中是替代了父类那个虚函数的位置,根据向上规则,就实现了多态。
#include<iostream> using namespace std; class base { public: virtual void print() { cout << "base::print()" << endl; } virtual void goo() { cout << "base::goo()" << endl; } }; class devired :public base { public: virtual void print() { cout << "devired::print()" << endl; } virtual void go() { cout << "devired::go()" << endl; } }; int main(void) { devired b; typedef void(*Fun)(void); Fun pfun = NULL; for (int i = 0; i < 3; i++) { pfun = (Fun)*((int*)*(int*)(&b)+i); pfun(); } system("pause"); }
#include<iostream> using namespace std; class point { public: virtual ~point() { cout << "~point()" << endl; } virtual point& mult(float) = 0; float x()const { return _x; } virtual float y()const { return 0; } virtual float z()const { return 0; } protected: point(float x = 0.0) {}; float _x; }; class point2 :public point { protected: float _y; public: point2(float x = 0.0, float y = 0.0):point(x),_y(y){} ~point2() { cout << "~point2()" << endl; } point2& mult(float); float y()const { return _y; } }; class point3 :public point2 { protected: float _z; public: point3(float x=0.0,float y=0.0,float z=0.0):point2(x,y),_z(z){} ~point3() { cout << "~point3()" << endl; } point3&mult(float); float z()const { return _z; } }; void main(void) { }
相关文章推荐
- C++中的动态类型与动态绑定、虚函数、运行时多态的实现
- C++中为什么要用虚函数、指针或引用才能实现多态?
- 利用虚函数实现多态
- C++中的动态类型与动态绑定、虚函数、运行时多态的实现
- 多态实现之虚函数
- 虚函数如何实现多态
- 虚函数如何实现多态
- 虚函数表 与 虚函数实现多态时应注意的问题
- 通过 虚函数 来实现多态
- C++多态实现(虚函数,成员函数覆盖、隐藏)
- c++ 虚函数实现多态的原理
- C++虚函数实现多态
- 【Linux基础】用虚函数实现动态多态的机制
- 虚函数实现多态的很好的例子。
- 多态三种实现:虚函数,抽象方法,接口
- C++对象布局及多态实现之带虚函数的类
- 为什么要使用虚函数和 指针(或是引用)才能实现多态?
- 虚函数实现多态
- 虚函数(实现多态)
- C++对象布局及多态实现探索之虚函数调用