C++多态案例

本文通过两个案例介绍了C++中的多态性,包括静态多态(函数重载和运算符重载)和动态多态(派生类与虚函数)。静态多态在编译时确定函数,动态多态在运行时决定。多态需要继承关系和虚函数,其优点在于代码结构清晰、可读性强和易于扩展维护。案例一展示了如何使用多态实现计算器的四种运算,案例二则展示了通过多态制作不同饮品的过程。
摘要由CSDN通过智能技术生成

多态简介

1.静态多态:函数重载和运算符重载属于静态多态,复用函数名
2.动态多态:派生类和虚函数实现运行多态

两者区别:

1.静态多态的函数地址早绑定——编译阶段确定函数地址
2.动态多态函数地址晚绑定——运行阶段确定函数地址

多态满足条件

1.有继承关系
2.子类重写父类中的虚函数

多态使用条件

父类指针或引用指向子类对象
重写:函数返回值类型,函数名,参数列表完全一致称为重写

多态的优点

1.代码组织结构清晰
2.可读性强
3.利于前期和后期的扩展和维护

案例一.计算器

#include<iostream>
using namespace std;

class Calculator
{
public:
	//纯虚函数,抽象类
	virtual int get_Result() = 0;
	int n_A=0;
	int n_B=0;
};
class Addition :public Calculator
{
public:
	int get_Result()
	{
		return n_A + n_B;
	}
};
class Subtraction :public Calculator
{
	int get_Result()
	{
		return n_A - n_B;
	}
};
class Multiplication :public Calculator
{
	int get_Result()
	{
		return n_A * n_B;
	}
};
class Division :public Calculator
{
	int get_Result()
	{
		return n_A / n_B;
	}
};
//测试加法
void test()
{
	Calculator* p = new Addition;
	p->n_A = 100;
	p->n_B = 150;
	cout << "n_A+n_B="
		<< p->get_Result()
		<< endl;
	delete p;
}
//测试减法
void test2()
{
	Calculator* p = new Subtraction;
	p->n_A = 100;
	p->n_B = 150;
	cout << "n_A-n_B="
		<< p->get_Result()
		<< endl;
	delete p;
}
int main()
{
	test();
	test2();
	return 0;
}

案例二.制作饮品

#include<iostream>
using namespace std;
class AbstractDringking
{
public:
	virtual void Boil() = 0;
	virtual void Brew() = 0;
	virtual void PourInCup() = 0;
	virtual void Addmore() = 0;
	virtual void Done() = 0;
	//proceduer
	void Procedure()
	{
		Boil();
		Brew();
		PourInCup();
		Addmore();
		Done();
	}
};
class Coffee :public AbstractDringking
{
public:
	virtual void Boil()
	{
		cout << "Heat the water" << endl;
	}
	virtual void Brew()
	{
		cout << "Brew coffee" << endl;
	}
	virtual void PourInCup()
	{
		cout << "Pour the coffee into the cup" << endl;
	}
	virtual void Addmore()
	{
		cout << "Add milk" << endl;
	}
	virtual void Done()
	{
		cout << "Your coffee is finished" << endl;
	}
};
class Tea :public AbstractDringking
{
public:
	void Boil()
	{
		cout << "Heat the water" << endl;
	}
	void Brew()
	{
		cout << "Brewing tea" << endl;
	}
	void PourInCup()
	{
		cout << "Pour the tea into the cup" << endl;
	}
	void Addmore()
	{
		cout << "Add medlar" << endl;
	}
	void Done()
	{
		cout << "Your tea is finished" << endl;
	}
};

//Business function
void DoWork(AbstractDringking* drink)
{
	drink->Procedure();
	delete drink;
}
void test()
{
	AbstractDringking* p1 = new Coffee;
	DoWork(p1);
	cout << "--------------" << endl;
	AbstractDringking* p2 = new Tea;
	DoWork(p2);
}
int main()
{
	test();
	return 0;
}
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值