题解 | #多态实现计算器功能#

多态实现计算器功能

https://www.nowcoder.com/practice/f5e0b2ea13ee40308fcc275c0d06053f

#include <iostream>
using namespace std;

class BaseCalculator {
  public:
    int m_A;
    int m_B;
    // write your code here......
    virtual int getResult();//error! 在类外面的函数不能是虚函数

};

// 加法计算器类
class AddCalculator : public BaseCalculator {
    // write your code here......
    virtual int getResult() {
        int res = this->m_A + this->m_B;
        return res;
    }


};

// 减法计算器类
class SubCalculator : public BaseCalculator {
    // write your code here......
    virtual int getResult() {
        int res = this->m_A - this->m_B;
        return res;
    }

};


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;
}

全部评论

相关推荐

把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务