用c++定义一个抽象类 Shape包含抽象方法 double area()和 double perimeter()定义三个分别表示圆形、矩形和三角形的派生类,分别计算出矩形和圆形的面积。定义一个函数 void printShapelnfo(Shape& shape)输出传入的形状的面积和周长
时间: 2023-02-16 19:08:24 浏览: 157
下面是用 C++ 实现的代码:
```
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0;
virtual double perimeter() = 0;
};
class Circle: public Shape {
private:
double radius;
public:
Circle(double r): radius(r) {}
double area() {
return 3.14 * radius * radius;
}
double perimeter() {
return 2 * 3.14 * radius;
}
};
class Rectangle: public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h): width(w), height(h) {}
double area() {
return width * height;
}
double perimeter() {
return 2 * (width + height);
}
};
class Triangle: public Shape {
private:
double a;
double b;
double c;
public:
Triangle(double a, double b, double c): a(a), b(b), c(c) {}
double area() {
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
double perimeter() {
return a + b + c;
}
};
void printShapeInfo(Shape* shape) {
cout << "面积: " << shape->area() << endl;
cout << "周长: " << shape->perimeter() << endl;
}
int main() {
Circle circle(5);
cout << "圆形信息: " << endl;
printShapeInfo(&circle);
Rectangle rectangle(3, 4);
cout << "矩形信息: " << endl;
printShapeInfo(&rectangle);
Triangle triangle(3, 4, 5);
cout << "三角形信息: " << endl;
printShapeInfo(&triangle);
return 0;
}
```
在上述代码中,我们定义了一个名为 `Shape` 的抽象类,包含两个抽象方法 `area` 和 `perimeter`。然后我们定义了三个派生类:`Circle`、`Rectangle` 和 `Triangle`,分别表示圆形、矩形和三角形。每个派生类都覆盖了父类的抽象方法,并在方法中计算出对应图形的面积
阅读全文