定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea( )函数计算对象的面积,再使用Rectangle类创建一个派生类Square。在主函数中测试Rectangle、Circle和Square这三个类。
时间: 2024-02-12 10:06:12 浏览: 98
以下是实现代码:
```c++
#include<iostream>
using namespace std;
class Shape {
public:
virtual double getArea() = 0; //纯虚函数,必须在派生类中实现
};
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double getArea() {
return length * width;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double getArea() {
return 3.14 * radius * radius;
}
};
class Square : public Rectangle {
public:
Square(double side) : Rectangle(side, side) {}
};
int main() {
Rectangle rect(3, 4);
Circle circle(5);
Square square(6);
cout << "The area of the rectangle is " << rect.getArea() << endl;
cout << "The area of the circle is " << circle.getArea() << endl;
cout << "The area of the square is " << square.getArea() << endl;
return 0;
}
```
输出结果:
```
The area of the rectangle is 12
The area of the circle is 78.5
The area of the square is 36
```
阅读全文