写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆形)、Square(正方形)、Rectangle(矩形)。利用指针、虚函数printArea()、printLength()分别输出以上三者的面积和周长,三个图形的数据在定义对象时给定。另外实现一个通用的函数计算面积和周长,而不需要考虑是何种图形。
时间: 2024-02-16 10:03:53 浏览: 19
好的,以下是程序实现:
```c++
#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 M_PI * radius * radius; }
double getLength() { return 2 * M_PI * radius; }
void printArea() { cout << "圆形面积是:" << getArea() << endl; }
void printLength() { cout << "圆形周长是:" << getLength() << endl; }
private:
double radius;
};
class Square : public Shape {
public:
Square(double l) { length = l; }
double getArea() { return length * length; }
double getLength() { return 4 * length; }
void printArea() { cout << "正方形面积是:" << getArea() << endl; }
void printLength() { cout << "正方形周长是:" << getLength() << endl; }
private:
double length;
};
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;
};
void printInfo(Shape* shape) {
shape->printArea();
shape->printLength();
}
int main() {
Circle c(3);
Square s(4);
Rectangle r(2, 3);
printInfo(&c);
printInfo(&s);
printInfo(&r);
cout << "------------------------" << endl;
Shape* shapes[3];
shapes[0] = &c;
shapes[1] = &s;
shapes[2] = &r;
for (int i = 0; i < 3; i++) {
cout << "第" << i + 1 << "个图形的面积和周长:" << endl;
shapes[i]->printArea();
shapes[i]->printLength();
cout << endl;
}
return 0;
}
```
程序的核心是抽象基类Shape及其三个派生类,其中Shape是抽象类,定义了纯虚函数getArea()、getLength()、printArea()和printLength(),这些函数在派生类中必须实现。每个派生类分别实现了Shape定义的四个纯虚函数,计算并输出了圆形、正方形和矩形的面积和周长。在程序中,我们定义了一个printInfo()函数,它利用Shape类指针作为参数,可以输出任何一种图形的面积和周长。最后,我们定义了一个Shape类指针数组,分别指向三个派生类对象,并使用循环输出了它们的面积和周长。
这样设计程序的好处是,可以方便地扩展新的图形类,只需要从Shape类派生出新的图形类,并实现getArea()、getLength()、printArea()和printLength()四个纯虚函数即可。而通用的函数printInfo()和Shape类指针数组可以不做修改,仍然可以输出新的图形类的面积和周长。