题解 | #重写子类计算逻辑#
重写子类计算逻辑
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 {
// 在子类中重写父类的calculate方法
public:
//父类中有构造函数,但不是默认构造函数,系统不会自动生成子类的默认构造函数,于是自己实现子类的构造函数
Sub(int x, int y):Base(x,y){}
void calculate(){
if (Base::getY()!=0)
cout << getX()/getY() << endl;
else cout << "Error" << endl;
}
};
int main() {
int x, y, z;
cin >> x;
cin >> y;
Sub sub(x, y);
sub.calculate();
return 0;
}
#你的秋招进展怎么样了##我的求职思考##零基础学习C++#
查看24道真题和解析