c++用函数实现圆类,矩形类,三角类面积,并写出代码
时间: 2024-03-07 22:48:53 浏览: 17
好的,下面是实现圆类、矩形类、三角形类面积的代码:
```c++
#include <iostream>
#include <cmath> // 引入数学函数库
using namespace std;
class Circle {
public:
Circle(double r) : radius(r) {}
double area() {
return M_PI * radius * radius; // M_PI 是 math.h 中定义的圆周率常量
}
private:
double radius;
};
class Rectangle {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() {
return width * height;
}
private:
double width;
double height;
};
class Triangle {
public:
Triangle(double b, double h) : base(b), height(h) {}
double area() {
return 0.5 * base * height;
}
private:
double base;
double height;
};
int main() {
Circle c(2.5);
Rectangle r(3, 4);
Triangle t(5, 6);
cout << "圆的面积:" << c.area() << endl;
cout << "矩形的面积:" << r.area() << endl;
cout << "三角形的面积:" << t.area() << endl;
return 0;
}
```
以上代码定义了三个类,分别是圆、矩形、三角形,每个类都有一个计算面积的方法 `area()`。在 `main()` 函数中创建了一个圆、一个矩形、一个三角形的对象,分别调用它们的 `area()` 方法计算出它们的面积,最后输出到控制台中。