用c++自己输入边长半径来计算面积,要求声明一个基类Shape(形状),其中包含一个方法来计算面积; 从Shape 派生两个类:Rectangle(矩形类)和Circle(圆形类); 从Rectangle 类派生正方形类Square; 分别实现派生类构造函数、析构函数及其它功能的成员函数; 创建各派生类的对象,观察构造函数、析构函数的调用次序; 计算不同对象的面积。
时间: 2023-08-18 17:05:08 浏览: 55
好的,我可以帮你解答这个问题。以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double getArea() = 0; // 纯虚函数
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {
cout << "Rectangle constructor called." << endl;
}
~Rectangle() {
cout << "Rectangle destructor called." << endl;
}
double getArea() {
return length * width;
}
};
class Square : public Rectangle {
public:
Square(double s) : Rectangle(s, s) {
cout << "Square constructor called." << endl;
}
~Square() {
cout << "Square destructor called." << endl;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {
cout << "Circle constructor called." << endl;
}
~Circle() {
cout << "Circle destructor called." << endl;
}
double getArea() {
return 3.14159 * radius * radius;
}
};
int main() {
Shape *s1, *s2, *s3; // 创建对象指针
s1 = new Rectangle(4, 5);
s2 = new Circle(6);
s3 = new Square(3);
cout << "The area of rectangle is: " << s1->getArea() << endl;
cout << "The area of circle is: " << s2->getArea() << endl;
cout << "The area of square is: " << s3->getArea() << endl;
delete s1;
delete s2;
delete s3;
return 0;
}
```
在上面的代码中,我们首先声明了一个基类 `Shape`,其中包含了一个纯虚函数 `getArea()` 来计算面积。然后我们从 `Shape` 派生了两个类 `Rectangle` 和 `Circle`,分别表示矩形和圆形。在 `Rectangle` 类中,我们声明了一个构造函数和析构函数,并重写了基类的 `getArea()` 函数来计算矩形的面积。在 `Circle` 类中也是同样的做法。此外,我们还从 `Rectangle` 类派生了一个 `Square` 类,表示正方形。在 `Square` 类中,我们重写了基类的构造函数,以便于创建正方形。
在 `main()` 函数中,我们创建了三个对象指针,分别指向 `Rectangle`、`Circle` 和 `Square` 类的对象。我们可以通过这些对象指针来调用相应的函数,计算出它们的面积。最后,我们释放了所有对象的内存空间,以免造成内存泄漏。
在整个程序运行过程中,我们可以观察到构造函数和析构函数的调用次序,以及不同对象的面积计算结果。