题解 | #KiKi设计类继承#
KiKi设计类继承
https://www.nowcoder.com/practice/699ba050e2704591ae3e62401a856b0e
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
class Shape {
private:
int x, y;
public:
Shape(int _x, int _y) : x(_x), y(_y) {}
virtual double GetArea() const = 0;
};
class Rectangle : public Shape {
private:
int length, width;
public:
Rectangle(int _x, int _y, int _length, int _width) : Shape(_x, _y),
length(_length), width(_width) {}
virtual double GetArea() const {
return length * width;
}
};
class Circle : public Shape {
private:
int radius;
public:
Circle(int _x, int _y, int _radius) : Shape(_x, _y), radius(_radius) {}
virtual double GetArea() const {
return 3.14 * radius * radius;
}
};
class Square : public Rectangle {
public:
Square(int _x, int _y, int _side) : Rectangle(_x, _y, _side, _side) {}
};
int main() {
int length, width, radius, side;
// 输入矩形的长和宽
cin >> length >> width;
Rectangle rectangle(0, 0, length, width);
cout << rectangle.GetArea() << endl;
// 输入圆的半径
cin >> radius;
Circle circle(0, 0, radius);
cout << circle.GetArea() << endl;
// 输入正方形的边长
cin >> side;
Square square(0, 0, side);
cout << square.GetArea() << endl;
return 0;
}
查看1道真题和解析