多态案例一-计算器类
一、普通方式实现计算器
//多态案例
//普通写法
class Caculator
{
public:
int getResult(string oper){
if (oper == "+") {
return mNum1 + mNum2;
}
else if (oper == "-") {
return mNum1 - mNum2;
}
else if (oper == "*") {
return mNum1 * mNum2;
}
//如果想扩展新的功能,需要修改源码
//在真正的开发中,提倡开闭原则,即对扩展进行开放,对修改进行关闭
}
int mNum1, mNum2;
};
void test01() {
//创建计算器对象
Caculator c;
c.mNum1 = 10;
c.mNum2 = 10;
cout << c.mNum1 << "+" << c.mNum2 << "=" << c.getResult("+") << endl;
cout << c.mNum1 << "-" << c.mNum2 << "=" << c.getResult("-") << endl;
cout << c.mNum1 << "*" << c.mNum2 << "=" << c.getResult("*") << endl;
}
二、多态方式
//利用多态实现计算器
// 多态带来的好处
// 1、组织结构清晰
// 2、可读性强
// 3、利用前期和后期的扩展及维护
//实现计算器抽象类
class AbstractCaculator
{
public:
virtual int getResult() {//虚函数
return 0;
}
int mNum1;
int mNum2;
};
//加法类计算器
class AddCaculator :public AbstractCaculator
{
public:
int getResult() {//重写
return mNum1 + mNum2;
}
};
//减法类计算器
class SubCaculator :public AbstractCaculator
{
public:
int getResult() {
return mNum1 - mNum2;
}
};
//乘法类计算器
class MulCaculator :public AbstractCaculator
{
public:
int getResult() {
return mNum1 * mNum2;
}
};
void test02() {
//多态使用条件
//父类指针或者引用指向子类对象
//加法运算
AbstractCaculator* abc = new AddCaculator;//父类指针指向子类对象
abc->mNum1 = 100;
abc->mNum2 = 100;
cout << abc->mNum1 << "+" << abc->mNum2 << "=" << abc->getResult() << endl;
//用完后记得销毁
delete abc;
//减法运算
abc = new SubCaculator;
abc->mNum1 = 100;
abc->mNum2 = 100;
cout << abc->mNum1 << "-" << abc->mNum2 << "=" << abc->getResult() << endl;
delete abc;
//乘法运算
abc = new MulCaculator;
abc->mNum1 = 100;
abc->mNum2 = 100;
cout << abc->mNum1 << "*" << abc->mNum2 << "=" << abc->getResult() << endl;
delete abc;
}