C++学习寄录(九.多态)

1.多态基本概念

先来看这样的代码,我的本意是想要输出"小猫在说话",但实际输出的却是"动物在说话"。这是因为地址早绑定,在代码编译阶段就已经确定了函数地址;如果想要实现既定目标,那么这个dospeak()函数就不能提前绑定,需要在运行阶段进行绑定,也就是地址晚绑定。

复制代码
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <ctime>
#include <thread>

using namespace std;

class animal{
	public:
	void speak(){
		std::cout << "动物在说话" << std::endl;
	}
};

class cat : public animal{
	public:
	void speak(){
		std::cout << "小猫在说话" << std::endl;
	}
};

void dospeak(animal &animal){
	animal.speak();
}


int main(){
	cat cat1;
	dospeak(cat1);


	return 0;
}

输出为

动物在说话

把父类的函数定义为虚函数,这样这个函数的地址就不是早绑定,他需要在代码运行时确定传入的对象,再来确定地址,这样便完成了地址晚绑定。

复制代码
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <ctime>
#include <thread>

using namespace std;

class animal{
	public:
	virtual void speak(){
		std::cout << "动物在说话" << std::endl;
	}
};

class cat : public animal{
	public:
	void speak(){
		std::cout << "小猫在说话" << std::endl;
	}
};

void dospeak(animal &animal){
	animal.speak();
}


int main(){
	cat cat1;
	dospeak(cat1);


	return 0;
}

输出为

小猫在说话

这样就叫做多态,多态满足条件

* 有继承关系

* 子类重写父类中的虚函数

多态使用条件

* 父类指针或引用指向子类对象

重写:函数返回值类型 函数名 参数列表 完全一致称为重写

2.纯虚函数和抽象类

在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容

因此可以将虚函数改为**纯虚函数**

纯虚函数语法:`virtual 返回值类型 函数名 (参数列表)= 0 ;`

当类中有了纯虚函数,这个类也称为==抽象类==

**抽象类特点**:

* 无法实例化对象

* 子类必须重写抽象类中的纯虚函数,否则也属于抽象类

复制代码
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <ctime>
#include <thread>

using namespace std;

class Animal
{
public:
	//纯虚函数
	//类中只要有一个纯虚函数就称为抽象类
	//抽象类无法实例化对象
	//子类必须重写父类中的纯虚函数,否则也属于抽象类
	virtual void func() = 0;
};

class Cat :public Animal
{
public:

	Cat(string name){
		name_t = new string(name);

	}
	virtual void func() 
	{
		cout << *name_t << "小猫在说话" << endl;	   //子类必须重写父类中的纯虚函数,否则也属于抽象类
	};

	string *name_t;
};

int main() {

	Animal *animal = new Cat("Tom");    // 抽象类无法实例化对象
	animal->func();
	delete animal;   //记得销毁

	return 0;
}

输出为

Tom小猫在说话

相关推荐
fwerfv34534540 分钟前
C++中的装饰器模式变体
开发语言·c++·算法
wjs20242 小时前
Perl 错误处理
开发语言
楼田莉子4 小时前
C++学习:C++11介绍及其新特性学习
开发语言·c++·学习·stl·visual studio
不枯石4 小时前
Matlab通过GUI实现点云的随机一致性(RANSAC)配准
开发语言·图像处理·算法·计算机视觉·matlab
牛马的人生4 小时前
MATLAB模块库入门:提升你的工程分析效率
开发语言·其他·matlab
光电笑映6 小时前
C++list全解析
c语言·开发语言·数据结构·c++·list
大白的编程日记.6 小时前
【Linux学习笔记】线程概念和控制(三)
linux·笔记·学习
恋猫de小郭7 小时前
Fluttercon EU 2025 :Let‘s go far with Flutter
android·开发语言·flutter·ios·golang
L_09077 小时前
【Algorithm】双指针算法与滑动窗口算法
c++·算法
小龙报7 小时前
《构建模块化思维---函数(下)》
c语言·开发语言·c++·算法·visualstudio·学习方法