题解 | #多态实现计算器功能#
多态实现计算器功能
https://www.nowcoder.com/practice/f5e0b2ea13ee40308fcc275c0d06053f
#include <iostream>
using namespace std;
class BaseCalculator {
public:
int m_A;
int m_B;
//声明getResult方法,并添加标识符virtual
virtual int getResult();
};
// 加法计算器类
class AddCalculator : public BaseCalculator {
//重载getResult方法,实现加法功能
virtual int getResult(){
return m_A+m_B;
}
};
// 减法计算器类
class SubCalculator : public BaseCalculator {
//重载getResult方法,实现减法功能
virtual int getResult(){
return m_A-m_B;
}
};
int main() {
BaseCalculator* cal = new AddCalculator;
cal->m_A = 10;
cal->m_B = 20;
cout << cal->getResult() << endl;
delete cal;
cal = new SubCalculator;
cal->m_A = 20;
cal->m_B = 10;
cout << cal->getResult() << endl;
delete cal;
return 0;
}
安克创新 Anker公司福利 716人发布