C++多态案例

多态简介

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

两者区别:

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

多态满足条件

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

多态使用条件

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

多态的优点

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

案例一.计算器

#include
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
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;
}

你可能感兴趣的:(C++面向对象,C++学习笔记,c++,开发语言,后端)