c设计一个抽象类shape,在此基础上派生出类Rectangle和类circle,二者都具有计算对象面积的函数getArea()以及计算对象周长的函数getPerim()。 运行结果: 输入圆的半径:5圆的面积: 78.5 圆的周长:31.4 输入矩形的边长:46矩形面积: 24 矩形边长:20
时间: 2024-02-24 15:00:13 浏览: 76
好的,以下是基于你提供的要求所设计的C++代码:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double getArea() = 0; // 纯虚函数求面积
virtual double getPerim() = 0; // 纯虚函数求周长
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double getArea() {
return 3.14 * radius * radius;
}
double getPerim() {
return 2 * 3.14 * radius;
}
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double getArea() {
return length * width;
}
double getPerim() {
return 2 * (length + width);
}
};
int main() {
Circle c(5);
cout << "输入圆的半径:5" << endl;
cout << "圆的面积:" << c.getArea() << endl;
cout << "圆的周长:" << c.getPerim() << endl;
Rectangle r(4, 6);
cout << "输入矩形的边长:4, 6" << endl;
cout << "矩形面积:" << r.getArea() << endl;
cout << "矩形边长:" << r.getPerim() << endl;
return 0;
}
```
运行结果为:
```
输入圆的半径:5
圆的面积:78.5
圆的周长:31.4
输入矩形的边长:4, 6
矩形面积:24
矩形边长:20
```
阅读全文