类的组合,线段(Line)类
时间: 2024-06-03 15:03:59 浏览: 26
类的组合是指在一个类中使用其他类的对象作为其成员变量。对于线段(Line)类来说,可以通过组合其他类来实现一些功能。
例如,可以创建一个点(Point)类来表示线段的起点和终点,然后在线段类中使用两个点对象作为成员变量。这样,线段类就可以通过调用点对象的方法来计算线段的长度、判断线段是否平行等操作。
下面是一个示例代码:
```cpp
class Point {
private:
int x;
int y;
public:
Point(int x, int y) {
this->x = x;
this->y = y;
}
// 其他方法...
};
class Line {
private:
Point start; // 起点
Point end; // 终点
public:
Line(Point start, Point end) {
this->start = start;
this->end = end;
}
// 其他方法...
};
```
通过以上代码,我们可以创建一个线段对象,并使用点对象来表示线段的起点和终点。这样,我们就可以通过线段对象调用点对象的方法来进行相关操作。
相关问题
定义一个点类CPoint,定义一个线段类Cline,计算线段长度。使用类的组合(对象成员)实现
下面是一个简单的实现:
```
#include <cmath>
#include <iostream>
// 定义点类
class CPoint {
public:
double x;
double y;
CPoint(double x, double y) : x(x), y(y) {}
// 计算两个点之间的距离
double distance(CPoint other) {
double dx = x - other.x;
double dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
};
// 定义线段类
class CLine {
public:
CPoint start;
CPoint end;
CLine(CPoint start, CPoint end) : start(start), end(end) {}
// 计算线段长度
double length() {
return start.distance(end);
}
};
int main() {
CPoint p1(0, 0);
CPoint p2(3, 4);
CLine line(p1, p2);
std::cout << "线段长度为:" << line.length() << std::endl;
return 0;
}
```
在这个实现中,点类 CPoint 定义了一个 distance() 方法,用于计算两个点之间的距离。线段类 CLine 定义了一个 length() 方法,用于计算线段的长度。在 main() 函数中,我们首先创建了两个点对象 p1 和 p2,然后用它们来创建一个线段对象 line。最后,我们调用了 line.length() 方法来输出线段的长度。这里使用了类的组合(对象成员)的方式,即线段类中包含了两个点对象。
设计一个组合类Line,其数据成员有point类定义的对象start与end,成员函数包括构造函数、析构函数、求线段对象长度、线段平移等
class Point {
private:
double x, y;
public:
Point(double x = 0, double y = 0) : x(x), y(y) {}
double getX() const { return x; }
double getY() const { return y; }
};
class Line {
private:
Point start, end;
public:
Line(const Point& start, const Point& end) : start(start), end(end) {}
~Line() {}
double length() const {
double dx = start.getX() - end.getX();
double dy = start.getY() - end.getY();
return sqrt(dx * dx + dy * dy);
}
void translate(double dx, double dy) {
start = Point(start.getX() + dx, start.getY() + dy);
end = Point(end.getX() + dx, end.getY() + dy);
}
};