多态对象模型
来源:互联网 发布:家用健身器材 知乎 编辑:程序博客网 时间:2024/06/05 22:34
一、多态
多态即多种形态,在c++中分为静态多态和动态多态,
静态多态:重载,编译期间决议确定。
动态多态:通过继承重写基类的虚函数实现的多态。
二、多态对象模型
单继承:
#include <iostream>using namespace std;class Base{public: virtual void func1() { cout << "Base::fun1()" << endl; } virtual void func2() { cout << "Base::fun1()" << endl; }public: int a;};class Derive:public Base{public: virtual void func1() { cout << "Derive::fun1()" << endl; } virtual void func3() { cout << "Derive::fun3()" << endl; } virtual void func4() { cout << "Derive::fun4()" << endl; }public: int b;};typedef void(*V_FUNC)();void PrintVTable(int* vtable){ printf("虚函数表:[%p]\n",vtable); for (size_t i = 0; vtable[i]; ++i) { printf("vfunc[%d]:%p->", i, vtable[i]); V_FUNC f = (V_FUNC)vtable[i]; f(); } cout << "====================" << endl;}int main(){ Base b; Derive d; int* VTable = (int*)(*((int*)(&d))); PrintVTable(VTable); PrintVTable((int*)(*((int*)&b))); b.func1(); b.func2(); d.func1(); d.func2(); d.func3(); d.func4(); system("pause"); return 0;}
多继承:
#include <iostream>using namespace std;class Base1{public: virtual void f1() { cout << "Base1::f1()" << endl; } virtual void f2() { cout << "Base1::f2()" << endl; }};class Base2{public: virtual void f1() { cout << "Base2::f1()" << endl; } virtual void f2() { cout << "Base2::f2()" << endl; }};class Derive :public Base1, public Base2{public: virtual void f1() { cout << "Derive::f1()" << endl; } virtual void f3() { cout << "Derive::f3()" << endl; }};typedef void(*V_FUNC)();void PrintVTable(int* vtable){ printf("虚函数表:[%p]\n", vtable); for (size_t i = 0; vtable[i]; ++i) { printf("vfunc[%d]:%p->", i, vtable[i]); V_FUNC f = (V_FUNC)vtable[i]; f(); } cout << "====================" << endl;}int main(){Base1 b1; Base2 b2; Derive d; int* VTable = (int*)(*((int*)(&b1))); PrintVTable(VTable); PrintVTable((int*)(*((int*)&b2))); PrintVTable((int*)(*((int*)&d))); system("pause"); return 0;}
阅读全文
0 0
- 多态对象模型
- 多态&多态对象模型
- 多态&多态对象模型
- 多态及其对象模型
- 多态&多态对象模型
- 多态的对象模型
- 多态&多态对象模型
- 多态&多态对象模型
- 多态&多态对象模型
- 多态&多态对象模型
- 多态的对象模型
- 多态的对象模型
- 多态+多态对象模型
- 多态+多态对象模型
- 多态&多态对象模型
- 多态+多态对象模型
- 多态与对象模型
- 多态及其对象模型
- TestNG入门教程-15-Java语言的断言和Junit的断言
- LeetCode [10. Regular Expression Matching]
- 二元运算符的运算符重载
- python爬虫(BeautifulSoup)
- python:数据类型
- 多态对象模型
- Git安装及使用文章网址收录
- 自然语言处理
- python入门运算(shape 、tile 、sum)
- VS2017+PCL1.8.1+Cmake(3.6 or later)环境配置
- 第十一周项目二——操作用邻接表存储的图
- chrome文件上传 /获取文件路径c:/fakepath的解决办法
- 深度学习第一课 第四周 深层神经网络用python的实现
- leetcode 446. Arithmetic Slices II