c++ 多态案例----计算器类

多态案例----计算器类

案例描述
利用C++多态实现两个操作数进行运算的计算器类

多态的优点:

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

示例:

#include 
#include 

using namespace std;
class CAbstractCalculate
{
public:
	virtual int getResult()
	{
		return 0;
	}
	int m_Num1;
	int m_Num2;
};

class CAdd :public CAbstractCalculate
{
	int getResult()
	{
		return m_Num1+ m_Num2;
	}
};

class CSub :public CAbstractCalculate
{
	int getResult()
	{
		return m_Num1 - m_Num2;
	}
};

class CMul :public CAbstractCalculate
{
	int getResult()
	{
		return m_Num1 * m_Num2;
	}
};


int main()
{
	CAbstractCalculate * abs = new CAdd;
	abs->m_Num1 = 10;
	abs->m_Num2 = 20;
	cout << abs->m_Num1 << "+" << abs->m_Num2 << " = " << abs->getResult() << endl;
	delete abs;

	abs = new CSub;
	abs->m_Num1 = 50;
	abs->m_Num2 = 10;
	cout << abs->m_Num1 << "-" << abs->m_Num2 << " = " << abs->getResult() << endl;
	delete abs;

	abs = new CMul;
	abs->m_Num1 = 3;
	abs->m_Num2 = 4;
	cout << abs->m_Num1 << "*" << abs->m_Num2 << " = " << abs->getResult() << endl;
	delete abs;


	system("pause");
	return 0;
}

总结:C++开发提倡利用多态设计程序架构,因为多态优点很多。

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