55类和对象-多态-案例1-计算器类

#include
#include
using namespace std;
//分别利用普通写法和多态技术实现计算器
//普通写法
class Calculator
{
public:
	int getResult(string oper)
	{
		if (oper == "+")
		{
			return m_Num1 + m_Num2;
		}
		else if(oper == "-")
		{
			return m_Num1 - m_Num2;
		}
		else if (oper == "*")
		{
			return m_Num1 * m_Num2;
		}
		//如果想扩展新的功能,需要修改源码
		//在真实的开发中 提倡开闭原则
		//开闭原则:对扩展进行开发,对系应该进行关闭
	}
	int m_Num1;//操作数1
	int m_Num2;//操作数2
};
void test01()
{
	//创建计算器对象
	Calculator c;
	c.m_Num1 = 10;
	c.m_Num2 = 10;
	cout << c.m_Num1 << "+" << c.m_Num2 <<"=" <m_Num1 = 10;
	abc->m_Num2 = 10;
	cout << abc->m_Num1 << "+" << abc->m_Num2 << "=" << abc->Getresult() <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 = 10;
	abc->m_Num2 = 10;
	cout << abc->m_Num1 << "*" << abc->m_Num2 << "=" << abc->Getresult() << endl;
	delete abc;
}
int main()
{
	// test01();
	test02();
	system("pause");//按任意键继续
	return 0;//关闭程序
}	

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

你可能感兴趣的:(C++学习网课笔记,c++,算法,数据结构)