题解 | #重写子类计算逻辑#

重写子类计算逻辑

https://www.nowcoder.com/practice/8521afcde7d147bf9975352fc5f3fb7c

#include <iostream>
using namespace std;

class Base {

  private:
    int x;
    int y;

  public:
    Base(int x, int y) {
        this->x = x;
        this->y = y;
    }

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }

    void calculate() {
        cout << getX() * getY() << endl;
    }

};

class Sub : public Base {
// write your code here......
  public:
    Sub (int x, int y): Base(x, y)
    {}
    void calculate() {
        if (getY() == 0) {
            cout << "Error" << endl;
        } else {

            cout << getX() / getY() << endl;
        }
    }
};

int main() {

    int x, y, z;
    cin >> x;
    cin >> y;
    Sub sub(x, y);
    sub.calculate();

    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务