定义一个点类CPoint,定义一个线段长度。使用类的组合(对象成员)实现
时间: 2023-07-10 11:18:55 浏览: 51
好的,下面是C++的代码实现:
```cpp
class CPoint {
public:
CPoint(int x, int y) : m_x(x), m_y(y) {}
private:
int m_x;
int m_y;
};
class CLine {
public:
CLine(CPoint start, CPoint end) : m_start(start), m_end(end) {
// 计算线段长度
m_length = sqrt(pow(m_start.m_x - m_end.m_x, 2) + pow(m_start.m_y - m_end.m_y, 2));
}
private:
CPoint m_start;
CPoint m_end;
double m_length;
};
```
上面的代码中,我们定义了一个CPoint类表示二维平面上的一个点,然后定义了一个CLine类表示一条线段,其中包含了起点和终点两个CPoint对象成员,通过这两个成员可以计算出线段的长度。这就是类的组合,即一个类的成员变量是另一个类的对象。
相关问题
定义一个点类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() 方法来输出线段的长度。这里使用了类的组合(对象成员)的方式,即线段类中包含了两个点对象。
定义一个点类CPoint,定义一个线段类CLine,计算线段长度。使用类的组合(对象成员)实现
好的,我来为您解答这个问题。
首先,我们需要定义点类CPoint。点类CPoint可以包括两个私有成员变量x和y,分别表示点的横坐标和纵坐标。同时,我们还可以定义一个公有成员函数,用于设置点的坐标。
```c++
class CPoint {
public:
CPoint() : x(0), y(0) {}
CPoint(double x_, double y_) : x(x_), y(y_) {}
void set(double x_, double y_) { x = x_; y = y_; }
private:
double x;
double y;
};
```
接下来,我们需要定义线段类CLine。线段类CLine可以包括两个私有成员变量p1和p2,分别表示线段的起点和终点。同时,我们还可以定义一个公有成员函数,用于计算线段长度。
```c++
#include <cmath>
class CLine {
public:
CLine() {}
CLine(CPoint p1_, CPoint p2_) : p1(p1_), p2(p2_) {}
double length() const {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return std::sqrt(dx * dx + dy * dy);
}
private:
CPoint p1;
CPoint p2;
};
```
最后,我们可以使用类的组合(对象成员)实现计算线段长度。具体而言,我们可以在主函数中创建两个点对象p1和p2,然后将它们作为参数传递给线段对象l1,最后调用l1的length函数即可计算出线段的长度。
```c++
int main() {
CPoint p1(0, 0), p2(3, 4);
CLine l1(p1, p2);
double len = l1.length();
std::cout << "The length of line l1 is " << len << std::endl;
return 0;
}
```
以上就是使用类的组合(对象成员)实现计算线段长度的方法。希望能够对您有所帮助!