今天介绍的是一个多态的案例 分别利用普通写法和多态写法,设计实现两个操作数进行运算的计算机类
多态的优点: 1、代码组织结构性强 2、代码可读性强 3、便于以后代码的维护和扩展
普通写法:
class Calculator
{
public:
//获取计算结果
int getresult(string oper)
{
if (oper == "+")
{
return num1 + num2;
}
else if (oper == "-")
{
return num1 - num2;
}
else if (oper == "*")
{
return num1 * num2;
}
else if (oper == "/")
{
return num1 / num2;
}
}
int num1;
int num2;
};
int main()
{
Calculator sp;
sp.num1 = 20;
sp.num2 = 30;
cout << "相加的结果是" << sp.getresult("+") << endl;
}
如果我们再添加其他运算符的话就只能动类中的代码,不便于后期的维护
多态:
class DivCalculator :public Calculator
{
public:
int getresult()
{
return num1 / num2;
}
};
int main()
{
//创建类对象
//在堆区new计算器出来
Calculator* add = new AddCalculator;
add->num1 = 20;
add->num2 = 30;
cout << "加法:" <<" "<< add->getresult() << endl;;
delete add;
//创建减法计算器
Calculator* sub = new SubCalculator;
sub->num1 = 50;
sub->num2 = 20;
cout << "减法:" << " " << sub->getresult() << endl;
delete sub;
//创建乘法计算器
Calculator* mul = new MulCalculator;
mul->num1 = 50;
mul->num2 = 20;
cout <<"乘法:" << " " << mul->getresult() << endl;
delete mul;
//创建除法计算器
Calculator* div = new DivCalculator;
div->num1 = 50;
div->num2 = 20;
cout << "除法是:" << " " << div->getresult() << endl;
delete div;
return 0;
}
虽然说代码量多了,但是代码的可读性强,便于后期的维护和扩展,在堆上开辟的空间最后一定要释放.
如有错误,多多指教!