多态案例-计算器类

发布时间:2023年12月28日

案例描述:

分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类

多态的优点:

1.代码组织结构清晰

2.可读性强

3.利于前期和后期的扩展以及维护

示例:

#include<iostream>
using namespace std;
//普通计算机实现
class Calculator
{
public:
	int getoper(string oper)
	{
		if (oper == "+")
		{
			return num1 + num2;
		}
		else if (oper == "-")
		{
			return num1 - num2;
		}
		else if (oper == "*")
		{
			return num1 * num2;
		}
	}
	//如果是想扩展新的功能,需要修改源码
	//在真实开发中 提倡 开闭原则
	//开闭原则:对扩展进行开放,对修改进行关闭
	int num1;//操作数1
	int num2;//操作数2
};
void test01()
{
	Calculator c;
	c.num1 = 10;
	c.num2 = 10;
	cout << c.num1 << "+" << c.num2 << " = " << c.getoper("+") << endl;
	cout << c.num1 << "-" << c.num2 << " = " << c.getoper("-") << endl;
	cout << c.num1 << "*" << c.num2 << " = " << c.getoper("*") << endl;
}
//利用多态实现计算器
//多态的好处:
// 1.组织结构清晰
// 2.可读性强
// 3.对于前期和后期扩展以及维护性高
 
//实现计算器抽象类
class AbstractCalculator
{
public:
	int virtual getResult()
	{
		return 0;
	}
	int m_Num1;
	int m_Num2;
};
//加法计算器类
class AddCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_Num1 + m_Num2;
	}
};
//减法计算器类
class CulCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_Num1 - m_Num2;
	}
};
//乘法计算器类
class MelCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_Num1 * m_Num2;
	}
};
class DelCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_Num1 / m_Num2;
	}
};
void test02()
{
	//多态使用条件
	//父类指针或者引用指向子类对象

	//加法计算
	AbstractCalculator* abc = new AddCalculator;
	abc->m_Num1 = 20;
	abc->m_Num2 = 20;
	cout << abc->m_Num1 << "+" << abc->m_Num2 << " = " << abc->getResult() << endl;
	delete abc;

	//减法计算
	abc = new CulCalculator;
	abc->m_Num1 = 20;
	abc->m_Num2 = 20;
	cout << abc->m_Num1 << "-" << abc->m_Num2 << " = " << abc->getResult() << endl;
	delete abc;

	//乘法计算
	abc = new MelCalculator;
	abc->m_Num1 = 20;
	abc->m_Num2 = 20;
	cout << abc->m_Num1 << "*" << abc->m_Num2 << " = " << abc->getResult() << endl;
	delete abc;

	//除法计算
	abc = new DelCalculator;
	abc->m_Num1 = 20;
	abc->m_Num2 = 20;
	cout << abc->m_Num1 << "/" << abc->m_Num2 << " = " << abc->getResult() << endl;
	delete abc;
}
int main()
{
	//test01();
	test02();
	return 0;
}

文章来源:https://blog.csdn.net/xms12_3/article/details/135267951
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。