4.7.2多态案列--计算机类

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

多态的优点:

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

 普通写法

#include
#include
using namespace std;


class Calculator
{
public:	
	int getResult(string optr)
	{
		if (optr == "+")
		{
			return m_Num1 + m_Num2;
		}
		else if (optr == "-")
		{
			return m_Num1 - m_Num2;
		}
		else if (optr == "*")
		{
			return  m_Num1 * m_Num2;
		}
		//如果想要扩展新的功能,需要修改源码
		//在真实的开发中 提倡开闭原则
		//开闭原则:对扩展进行开发,对修改进行关闭

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


int main()
{   
	test01(); 
	
	return 0;
}

 

 多态写法

//利用多态实现计算机
//实现计算器抽象类
class AbstractCalculator
{
public:
	virtual int getResult()
	{
		return 0;
	}
	int m_Num1;
	int m_Num2;
};

//加法计算器类
class AddCalculator :public AbstractCalculator
{
	int getResult()
	{
		return  m_Num1 + m_Num2;
	}
};

//减法计算器类
class SubCalculator :public AbstractCalculator
{
	int getResult()
	{
		return  m_Num1-m_Num2;
	}
};

//乘法计算器类
class MulCalculator :public AbstractCalculator
{
	int getResult()
	{
		return  m_Num1 * m_Num2;
	}
};

void test02()
{
	//多态使用条件
	//父类指针或者引用指向子类对象
	//加法运算
	AbstractCalculator *abc = new AddCalculator;
	abc->m_Num1 = 100;
	abc->m_Num2 = 100;

	cout << abc->m_Num1 << "+" << abc->m_Num2 << "=" << abc->getResult() << endl;

	//用完记得销毁
	delete  abc;

	//减法运算
	abc = new SubCalculator;
	abc->m_Num1 = 100;
	abc->m_Num2 = 100;

	cout << abc->m_Num1 << "-" << abc->m_Num2 << "=" << abc->getResult() << endl;
	//用完记得销毁
	delete  abc;

	//乘法运算
	abc = new MulCalculator;
	abc->m_Num1 = 100;
	abc->m_Num2 = 100;

	cout << abc->m_Num1 << "*" << abc->m_Num2 << "=" << abc->getResult() << endl;
	//用完记得销毁
	delete  abc;

}
int main()
{   
	test02(); 
	
	return 0;
}

 总结:C++中提倡利用多态设计程序框架,因为多态优点很多

你可能感兴趣的:(c++)