这篇文章只讲重点,会有点简略 适合略知多态但是对其不太明白的小伙伴
所谓多态 即多种形态
多态分为两种
一种为静态多态 包含:函数重载 运算符重载
另一种为动态多态 依我个人的理解就是在继承的成员函数上动点花样
这篇文章主要讲解个人对动态多态的理解 希望可以帮助到你们。
想要了解并使用动态多态 我们必须知道这些东西
- 继承
- 虚函数和纯虚函数
- 对虚函数或纯虚函数的重写
- C++支持父类对象类型转换为子类对象 (不可以子类转为父类)
下面我会一一对其进行讲解 (懂的小伙伴可以略过)
初步认识
继承
基本语法如下:
class father { public: int age; string ability; }; class son :public father { public: string hobby; };
虚函数和纯虚函数
基本语法如下:
class father { public: int age; string ability; //虚函数 virtual void Show_father_ability1() { } //纯虚函数 virtual void Show_father_ability2() = 0; };
重写
就是子类继承父类的虚函数或纯虚函数时
返回类型和参数都不变
对其执行内容进行改写
基本语法如下:(以纯虚函数为例)
class father { public: virtual void Show_father_ability2() = 0; }; class son :public father { public: string hobby; //对父类纯虚函数进行重写 void Show_father_ability2() { cout << "xxx" << endl; } };
父类对象转为子类对象
#include <iostream> using namespace std; class father { public: //纯虚函数 virtual void Show_father_ability2() = 0; }; class son :public father { public: string hobby; void Show_father_ability2() { cout << "xxx" << endl; } }; int main() { father* f = new son; //正确 //son* s = new father;//这样写是错的 return 0; }
深入理解
所谓多态 就是在继承时 把父类的纯虚函数继承给子类,让子类改写这个纯虚函数
可以由一个父类对象转换为多个子类的类型 操作其中的重写的函数
从而提高复用性
例子:
建立先看我讲解 按我的逻辑看代码 直接看代码有点不好懂
下面分别按顺序创建了三个类
worker类 Manage类 Employee类
职员类 经理类 普通职工类
职员包含于经理和职工 经理和普通职工没有继承关系
每个员工都有一个shoeInfo的函数 表明要展示职工信息
那么我们只需如图一 在worker类中加入showInfo的纯虚函数
然后将其重写 展示自己信息
然而我们应该怎么使用呢?
#pragma once #include <iostream> using namespace std; class Worker { public: virtual void showInfo() = 0; virtual string getDeptName() = 0; int m_ID; string m_name; int m_DeptID; };
#pragma once #include <iostream> using namespace std; #include "worker.h" class Manager:public Worker { public: Manager(int ID, string name, int dID); void showInfo(); string getDeptName(); };
#pragma once #include <iostream> using namespace std; #include "worker.h" class Employee :public Worker { public: Employee(int ID, string name, int dID); void showInfo(); string getDeptName(); };
纯虚函数使用例子
Worker* worker = NULL; //用Manage的showInfo worker = new Manager(10,"张三",1); worker->showInfo(); //释放Manager数据 指针还是存在的 delete worker; worker = NULL; //用Employee的showInfo worker = new Employee(10, "张三", 1); worker->showInfo(); //释放Employee数据 指针还是存在的 delete worker; worker = NULL;
感谢能够看到这里 希望这篇文章对大家有帮助