A line segment

Question:

In three-dimensional space, a line segment is defined by its two endpoints. Specify, design, and implement a class for a line segment. The class should have two private member variables that are points from the previous project.

My answer:

在point类声明中添加

double point::get_x() const
{
	return x;
}

double point::get_y() const
{
	return y;
}

double point::get_z() const
{
	return z;
}

line类声明

class line {
public:
	line(point m, point n) {
		p1 = m;
		p2 = n;
	}
	double length();
private:
	point p1, p2;
};

line类实现

double line::length()
{
	return sqrt(pow(p1.get_x() - p2.get_x(), 2) + pow(p1.get_y() - p2.get_y(), 2) + pow(p1.get_z() - p2.get_z(), 2));
}

 测试:

int main()
{
	point a(2.5, 0, 2.0);
	a.move_x(1);
	a.move_y(1.5);
	a.move_z(-2.5);
	a.rotate_x(PI / 2);
	a.rotate_y(PI / 4);
	a.rotate_z(3 * PI / 4);
	a.print_point();
	a.set_position(5, 5, 5);
	a.print_point();
	point b(3, 4, 5);
	line l(a, b);
	std::cout << "The length of l is " << l.length() << std::endl;
}

 结果:

A line segment_第1张图片

Reference:

整理自 Data Structures and Other Objects Using C++ ( Fourth Edition ) Michael Main, Walter Savitch. p121

你可能感兴趣的:(C++数据结构)