C++多态实现计算器

普通方法实现一个计算器


//普通实现
#include <iostream>
using namespace std;
#include <string>
class Calculator
{
public:
	int num1;
	int num2;
	//只有加减乘运算,如果后续需要增加减法,需要修改compute函数代码,不易扩展和维护
	int compute(string operation)
	{
		if (operation == "+")
			return num1 + num2;
		else if (operation == "-")
			return num1 - num2;
		else if (operation == "*")
			return num1 * num2;
		else
		{
			cout << "NO this Operation,Error\n";
			exit;
		}
	}
};
void test()
{
	Calculator c;
	c.num1 = 100;
	c.num2 = 200;
	cout << c.compute("+") << endl << c.compute("-") << endl << c.compute("*") << endl;
}
int main()
{
	test();
	return 0;
}

如果使用一般的方法写一个计算器,如果以后我想添加开方,开立方根等等的接口,就必须修改源码,修改源码不利于维护,所以我们要用到多态,用动态实现。

#include <iostream>
using namespace std;
//多态来实现计算器
class AbstractCalculator
{
public:
	int num1;
	int num2;
	//虚函数,用户实现多态
	virtual int compute() = 0;//纯虚函数
};
class AddCalculator : public AbstractCalculator
{
public:
	 virtual int compute()
	{
		return this->num1 + this->num2;
	}
};
class DelCalculator : public AbstractCalculator
{
public:
	virtual int compute()
	{
		return this->num1 - this->num2;
	}
};
class MulCalculator : public AbstractCalculator
{
public:
	virtual int compute()
	{
		return this->num1 * this->num2;
	}
};
//这里可以很方便的来扩展除法,而不需要修改上面的代码。如果哪个出现问题可以快速定位
class DivCalculator : public AbstractCalculator
{
public:
	virtual int compute()
	{
		return this->num1 / this->num2;
	}
};
void test01()
{
//多态的条件 父类条件或引用用于指向最类对象	
AbstractCalculator* abc = new AddCalculator;
	abc->num1 = 20;
	abc->num2 = 10;
	cout << abc->num1 << "+" << abc->num2 << "=" << abc->cmpute() << endl;
	delete abc;

	abc = new DelCalculator;
	abc->num1 = 20;
	abc->num2 = 10;
	cout << abc->num1 << "-" << abc->num2 << "=" << abc->compute() << endl;
	delete abc;

	abc = new MulCalculator;
	abc->num1 = 20;
	abc->num2 = 10;
	cout <<  abc->num1 << "*" << abc->num2 << "=" << abc->compute()  << endl;
	delete abc;

	abc = new DivCalculator;
	abc->num1 = 20;
	abc->num2 = 10;
	cout <<  abc->num1 << "/" << abc->num2 << "=" << abc->compute() << endl;
	delete abc;
}
int main()
{
	test01();
	return 0;
}

多态的优点:多态虽然会增加代码量但再拓展时候不用修改源码。组织结构清晰,可读性好,方便扩展和维护。    并且在开发中,提倡开闭原则,开闭原则是指对拓展开放,对修改关闭。

猜你喜欢

转载自blog.csdn.net/m0_74756975/article/details/129961284
今日推荐