写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆形)、Square(正方形)、Rectangle(矩形)。利用指针、虚函数printArea()、printLength()分别输出以上三者的面积和周长,三个图形的数据在定义对象时给定。另外实现一个通用的函数计算面积和周长,而不需要考虑是何种图形
时间: 2024-02-16 16:03:47 浏览: 117
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
好的,下面是实现了你提出的需求的C++代码:
```cpp
#include<iostream>
#include<cmath>
using namespace std;
class Shape {
public:
virtual double getArea() = 0;
virtual double getLength() = 0;
virtual void printArea() = 0;
virtual void printLength() = 0;
};
class Circle :public Shape {
public:
Circle(double r) :radius(r) {}
double getArea() { return radius * radius * 3.1415; }
double getLength() { return 2 * radius * 3.1415; }
void printArea() { cout << "圆的面积为:" << getArea() << endl; }
void printLength() { cout << "圆的周长为:" << getLength() << endl; }
private:
double radius;
};
class Square :public Shape {
public:
Square(double s) :side(s) {}
double getArea() { return side * side; }
double getLength() { return 4 * side; }
void printArea() { cout << "正方形的面积为:" << getArea() << endl; }
void printLength() { cout << "正方形的周长为:" << getLength() << endl; }
private:
double side;
};
class Rectangle :public Shape {
public:
Rectangle(double l, double w) :length(l), width(w) {}
double getArea() { return length * width; }
double getLength() { return 2 * (length + width); }
void printArea() { cout << "矩形的面积为:" << getArea() << endl; }
void printLength() { cout << "矩形的周长为:" << getLength() << endl; }
private:
double length;
double width;
};
double getTotalArea(Shape** arr, int n) {
double total = 0;
for (int i = 0; i < n; i++) {
total += arr[i]->getArea();
}
return total;
}
double getTotalLength(Shape** arr, int n) {
double total = 0;
for (int i = 0; i < n; i++) {
total += arr[i]->getLength();
}
return total;
}
int main() {
Shape* shapes[3];
shapes[0] = new Circle(2.5);
shapes[1] = new Square(4.0);
shapes[2] = new Rectangle(3.0, 4.0);
for (int i = 0; i < 3; i++) {
shapes[i]->printArea();
shapes[i]->printLength();
}
cout << "总面积为:" << getTotalArea(shapes, 3) << endl;
cout << "总周长为:" << getTotalLength(shapes, 3) << endl;
for (int i = 0; i < 3; i++) {
delete shapes[i];
}
return 0;
}
```
程序中定义了一个抽象基类Shape,有3个派生类:Circle、Square和Rectangle,分别表示圆形、正方形和矩形。每个派生类都实现了Shape类中的纯虚函数,分别计算图形的面积和周长,并输出结果。同时,还实现了两个通用函数getTotalArea()和getTotalLength(),分别计算所有图形的总面积和总周长。在main()函数中,分别创建3个Shape对象,并调用它们的函数输出结果。最后,清除所有对象并返回0。
阅读全文