C++程序(1)设计一个图形类,从其派生矩形,圆,三角形等类,设计计算图形面积函数f1,判断点是否在图形内部函数f2 (2)设计好类后,编写主函数进行测试。
时间: 2024-03-22 08:37:41 浏览: 102
以下是对应的C++代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
protected:
double area;
public:
virtual double f1() = 0;
virtual bool f2(double x, double y) = 0;
};
class Rectangle : public Shape {
private:
double length;
double width;
double x1, y1, x2, y2, x3, y3, x4, y4;
public:
Rectangle(double l, double w, double x, double y) : length(l), width(w) {
x1 = x; y1 = y;
x2 = x + length; y2 = y;
x3 = x + length; y3 = y + width;
x4 = x; y4 = y + width;
}
double f1() {
area = length * width;
return area;
}
bool f2(double x, double y) {
if (x > x1 && x < x3 && y > y1 && y < y3)
return true;
else
return false;
}
};
class Circle : public Shape {
private:
double radius;
double x, y;
public:
Circle(double r, double x0, double y0) : radius(r), x(x0), y(y0) {}
double f1() {
area = 3.14 * radius * radius;
return area;
}
bool f2(double x0, double y0) {
double d = sqrt((x0 - x) * (x0 - x) + (y0 - y) * (y0 - y));
if (d <= radius)
return true;
else
return false;
}
};
class Triangle : public Shape {
private:
double a, b, c;
double x1, y1, x2, y2, x3, y3;
public:
Triangle(double a0, double b0, double c0, double x0, double y0) : a(a0), b(b0), c(c0) {
x1 = x0; y1 = y0;
x2 = x0 + b0; y2 = y0;
x3 = x0 + (b0 * b0 + c0 * c0 - a0 * a0) / (2 * b0); y3 = y0 + sqrt(c0 * c0 - (x3 - x2) * (x3 - x2));
}
double f1() {
double p = (a + b + c) / 2;
area = sqrt(p * (p - a) * (p - b) * (p - c));
return area;
}
bool f2(double x0, double y0) {
double d1 = (x2 - x1) * (y0 - y1) - (y2 - y1) * (x0 - x1);
double d2 = (x3 - x2) * (y0 - y2) - (y3 - y2) * (x0 - x2);
double d3 = (x1 - x3) * (y0 - y3) - (y1 - y3) * (x0 - x3);
if ((d1 > 0 && d2 > 0 && d3 > 0) || (d1 < 0 && d2 < 0 && d3 < 0))
return true;
else
return false;
}
};
int main() {
Rectangle r(5.0, 3.0, 0, 0);
Circle c(4.0, 0, 0);
Triangle t(5.0, 4.0, 3.0, 0, 0);
cout << "Rectangle area: " << r.f1() << endl;
cout << "Point (1, 1) is in Rectangle? " << r.f2(1, 1) << endl;
cout << "Circle area: " << c.f1() << endl;
cout << "Point (3, 4) is in Circle? " << c.f2(3, 4) << endl;
cout << "Triangle area: " << t.f1() << endl;
cout << "Point (2, 2) is in Triangle? " << t.f2(2, 2) << endl;
return 0;
}
```
在这个程序中,我们首先定义了一个抽象基类 `Shape`,其中包含两个纯虚函数 `f1()` 和 `f2()`,分别用于计算图形的面积和判断点是否在图形内部。然后我们从这个基类中派生出三个类:`Rectangle`、`Circle` 和 `Triangle`,分别代表矩形、圆和三角形。
在每个派生类中,我们都实现了基类中的两个纯虚函数,并添加了一些额外的数据成员和函数。例如,在 `Rectangle` 类中,我们定义了矩形的长、宽和四个顶点的坐标,并在 `f2()` 函数中通过比较点的坐标和矩形顶点的坐标来判断点是否在矩形内部。
最后,在主函数中,我们创建了一个矩形、一个圆和一个三角形的对象,并分别调用它们的 `f1()` 和 `f2()` 函数来进行测试。
阅读全文