用C++写一个程序包含1.设计抽象基类Shape类 2.由Shape类派生出Circle圆类,Rectangle矩形类,Triangle三角形类 3.用函数printArea分别实现圆类、矩形类、三角形类的面积 4.用基类Shape类的指针输出圆类、矩形类、三角形类的面积
时间: 2024-03-03 18:53:38 浏览: 70
基于c++类的编写
好的,以下是一个完整的C++程序,包含1.设计抽象基类Shape类 2.由Shape类派生出Circle圆类,Rectangle矩形类,Triangle三角形类 3.用函数printArea分别实现圆类、矩形类、三角形类的面积 4.用基类Shape类的指针输出圆类、矩形类、三角形类的面积:
```c++
#include <iostream>
class Shape {
public:
virtual double getArea() = 0;
virtual void printArea() {
std::cout << "The area of the shape is: " << getArea() << std::endl;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() override {
return 3.14159 * radius * radius;
}
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double getArea() override {
return length * width;
}
};
class Triangle : public Shape {
private:
double base, height;
public:
Triangle(double b, double h) : base(b), height(h) {}
double getArea() override {
return 0.5 * base * height;
}
};
int main() {
Shape* circle = new Circle(5.0);
Shape* rectangle = new Rectangle(4.0, 6.0);
Shape* triangle = new Triangle(3.0, 5.0);
circle->printArea();
rectangle->printArea();
triangle->printArea();
delete circle;
delete rectangle;
delete triangle;
return 0;
}
```
在这个程序中,我们首先定义了抽象基类Shape类,并在其中定义了纯虚函数getArea()和虚函数printArea()。然后,我们派生出了Circle圆类、Rectangle矩形类和Triangle三角形类,并分别实现了它们的getArea()函数。最后,我们在主函数中通过基类Shape类的指针分别输出了圆、矩形和三角形的面积。
输出结果为:
```
The area of the shape is: 78.5398
The area of the shape is: 24
The area of the shape is: 7.5
```
可以看到,程序成功地输出了圆、矩形和三角形的面积。
阅读全文