定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea( )函数计算对象的面积,再使用Rectangle类创建一个派生类Square。在主函数中测试Rectangle、Circle和Square这三个类。
时间: 2024-02-12 21:06:12 浏览: 102
cs代码-1.仿圆类创建长方形类(Rectangle,包括长width和宽 height)和三角 形类(Triangle,包括边长:a,b,c); 2.为以上三类添加基类:Shape类。Shape类中包含形状名称(type) 和显示面积和周长等信息的方法:Display(). 3.创建测试类(Test),在测试类Main方法中实例化圆、长方形、三角形,并计算和显示这些几何形状的面积和周长。
以下是实现代码:
```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
```
阅读全文