文章内容转载自黑马程序员C++核心编程讲义,如有侵权,请联系作者删除
4.7 多态
4.7.1 多态的基本概念
多态是C++面向对象三大特性之一
多态分为两类
- 静态多态: 函数重载 和 运算符重载属于静态多态,复用函数名
- 动态多态: 派生类和虚函数实现运行时多态
静态多态和动态多态区别:
- 静态多态的函数地址早绑定 - 编译阶段确定函数地址
- 动态多态的函数地址晚绑定 - 运行阶段确定函数地址
下面通过案例进行讲解多态
class Animal { public: virtual void speak() { cout << "动物在说话" << endl; } };
class Cat :public Animal { public: void speak() { cout << "小猫在说话" << endl; } };
class Dog :public Animal { public:
void speak() { cout << "小狗在说话" << endl; }
};
void DoSpeak(Animal & animal) { animal.speak(); }
void test01() { Cat cat; DoSpeak(cat);
Dog dog; DoSpeak(dog); }
int main() {
test01();
system("pause");
return 0; }
|
总结:
多态满足条件
多态使用条件
重写:函数返回值类型 函数名 参数列表 完全一致称为重写
4.7.2 多态案例一-计算器类
案例描述:
分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类
多态的优点:
- 代码组织结构清晰
- 可读性强
- 利于前期和后期的扩展以及维护
示例:
class Calculator { public: int getResult(string oper) { if (oper == "+") { return m_Num1 + m_Num2; } else if (oper == "-") { return m_Num1 - m_Num2; } else if (oper == "*") { return m_Num1 * m_Num2; } } public: int m_Num1; int m_Num2; };
void test01() { Calculator c; c.m_Num1 = 10; c.m_Num2 = 10; cout << c.m_Num1 << " + " << c.m_Num2 << " = " << c.getResult("+") << endl;
cout << c.m_Num1 << " - " << c.m_Num2 << " = " << c.getResult("-") << endl;
cout << c.m_Num1 << " * " << c.m_Num2 << " = " << c.getResult("*") << endl; }
class AbstractCalculator { public :
virtual int getResult() { return 0; }
int m_Num1; int m_Num2; };
class AddCalculator :public AbstractCalculator { public: int getResult() { return m_Num1 + m_Num2; } };
class SubCalculator :public AbstractCalculator { public: int getResult() { return m_Num1 - m_Num2; } };
class MulCalculator :public AbstractCalculator { public: int getResult() { return m_Num1 * m_Num2; } };
void test02() { AbstractCalculator *abc = new AddCalculator; abc->m_Num1 = 10; abc->m_Num2 = 10; cout << abc->m_Num1 << " + " << abc->m_Num2 << " = " << abc->getResult() << endl; delete abc;
abc = new SubCalculator; abc->m_Num1 = 10; abc->m_Num2 = 10; cout << abc->m_Num1 << " - " << abc->m_Num2 << " = " << abc->getResult() << endl; delete abc;
abc = new MulCalculator; abc->m_Num1 = 10; abc->m_Num2 = 10; cout << abc->m_Num1 << " * " << abc->m_Num2 << " = " << abc->getResult() << endl; delete abc; }
int main() {
test02();
system("pause");
return 0; }
|
总结:C++开发提倡利用多态设计程序架构,因为多态优点很多
4.7.3 纯虚函数和抽象类
在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数
纯虚函数语法:virtual 返回值类型 函数名 (参数列表)= 0 ;
当类中有了纯虚函数,这个类也称为==抽象类==
抽象类特点:
- 无法实例化对象
- 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
示例:
class Base { public: virtual void func() = 0; };
class Son :public Base { public: virtual void func() { cout << "func调用" << endl; }; };
void test01() { Base * base = NULL; base = new Son; base->func(); delete base; }
int main() {
test01();
system("pause");
return 0; }
|
4.7.4 多态案例二-制作饮品
案例描述:
制作饮品的大致流程为:煮水 - 冲泡 - 倒入杯中 - 加入辅料
利用多态技术实现本案例,提供抽象制作饮品基类,提供子类制作咖啡和茶叶
示例:
class AbstractDrinking { public: virtual void Boil() = 0; virtual void Brew() = 0; virtual void PourInCup() = 0; virtual void PutSomething() = 0; void MakeDrink() { Boil(); Brew(); PourInCup(); PutSomething(); } };
class Coffee : public AbstractDrinking { public: virtual void Boil() { cout << "煮农夫山泉!" << endl; } virtual void Brew() { cout << "冲泡咖啡!" << endl; } virtual void PourInCup() { cout << "将咖啡倒入杯中!" << endl; } virtual void PutSomething() { cout << "加入牛奶!" << endl; } };
class Tea : public AbstractDrinking { public: virtual void Boil() { cout << "煮自来水!" << endl; } virtual void Brew() { cout << "冲泡茶叶!" << endl; } virtual void PourInCup() { cout << "将茶水倒入杯中!" << endl; } virtual void PutSomething() { cout << "加入枸杞!" << endl; } };
void DoWork(AbstractDrinking* drink) { drink->MakeDrink(); delete drink; }
void test01() { DoWork(new Coffee); cout << "--------------" << endl; DoWork(new Tea); }
int main() {
test01();
system("pause");
return 0; }
|
4.7.5 虚析构和纯虚析构
多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码
解决方式:将父类中的析构函数改为虚析构或者纯虚析构
虚析构和纯虚析构共性:
- 可以解决父类指针释放子类对象
- 都需要有具体的函数实现
虚析构和纯虚析构区别:
虚析构语法:
virtual ~类名(){}
纯虚析构语法:
virtual ~类名() = 0;
类名::~类名(){}
示例:
class Animal { public:
Animal() { cout << "Animal 构造函数调用!" << endl; } virtual void Speak() = 0;
virtual ~Animal() = 0; };
Animal::~Animal() { cout << "Animal 纯虚析构函数调用!" << endl; }
class Cat : public Animal { public: Cat(string name) { cout << "Cat构造函数调用!" << endl; m_Name = new string(name); } virtual void Speak() { cout << *m_Name << "小猫在说话!" << endl; } ~Cat() { cout << "Cat析构函数调用!" << endl; if (this->m_Name != NULL) { delete m_Name; m_Name = NULL; } }
public: string *m_Name; };
void test01() { Animal *animal = new Cat("Tom"); animal->Speak();
delete animal; }
int main() {
test01();
system("pause");
return 0; }
|
总结:
1. 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
2. 如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
3. 拥有纯虚析构函数的类也属于抽象类
4.7.6 多态案例三-电脑组装
案例描述:
电脑主要组成部件为
CPU(用于计算),显卡(用于显示),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
示例:
#include<iostream> using namespace std;
class CPU { public: virtual void calculate() = 0; };
class VideoCard { public: virtual void display() = 0; };
class Memory { public: virtual void storage() = 0; };
class Computer { public: Computer(CPU * cpu, VideoCard * vc, Memory * mem) { m_cpu = cpu; m_vc = vc; m_mem = mem; }
void work() { m_cpu->calculate();
m_vc->display();
m_mem->storage(); }
~Computer() {
if (m_cpu != NULL) { delete m_cpu; m_cpu = NULL; }
if (m_vc != NULL) { delete m_vc; m_vc = NULL; }
if (m_mem != NULL) { delete m_mem; m_mem = NULL; } }
private:
CPU * m_cpu; VideoCard * m_vc; Memory * m_mem; };
class IntelCPU :public CPU { public: virtual void calculate() { cout << "Intel的CPU开始计算了!" << endl; } };
class IntelVideoCard :public VideoCard { public: virtual void display() { cout << "Intel的显卡开始显示了!" << endl; } };
class IntelMemory :public Memory { public: virtual void storage() { cout << "Intel的内存条开始存储了!" << endl; } };
class LenovoCPU :public CPU { public: virtual void calculate() { cout << "Lenovo的CPU开始计算了!" << endl; } };
class LenovoVideoCard :public VideoCard { public: virtual void display() { cout << "Lenovo的显卡开始显示了!" << endl; } };
class LenovoMemory :public Memory { public: virtual void storage() { cout << "Lenovo的内存条开始存储了!" << endl; } };
void test01() { CPU * intelCpu = new IntelCPU; VideoCard * intelCard = new IntelVideoCard; Memory * intelMem = new IntelMemory;
cout << "第一台电脑开始工作:" << endl; Computer * computer1 = new Computer(intelCpu, intelCard, intelMem); computer1->work(); delete computer1;
cout << "-----------------------" << endl; cout << "第二台电脑开始工作:" << endl; Computer * computer2 = new Computer(new LenovoCPU, new LenovoVideoCard, new LenovoMemory);; computer2->work(); delete computer2;
cout << "-----------------------" << endl; cout << "第三台电脑开始工作:" << endl; Computer * computer3 = new Computer(new LenovoCPU, new IntelVideoCard, new LenovoMemory);; computer3->work(); delete computer3;
}
|