定义一个点类CPoint,定义一个线段类CLine,计算线段长度。使用类的组合(对象成员)实现
之前遇到过 可以讨论一下
点类包含 横坐标和纵坐标两个成员,线段类包含起点和终点两个成员, 其它可以再根据这两个成员来编写代码。
代码如下:
参考链接:
#include <iostream>
#include <math.h>
using namespace std;
// https://www.runoob.com/cplusplus/cpp-classes-objects.html
// 点类
class CPoint{
public :
double x; // 点的横坐标
double y; // 点的纵坐标
// https://www.runoob.com/cplusplus/cpp-constructor-destructor.html
CPoint();
CPoint(double x,double y);
void setX(double x);
double getX(void);
void setY(double y);
double getY(void);
};
CPoint::CPoint(void){
}
CPoint::CPoint(double dx,double dy){
x=dx;
y=dy;
}
void CPoint::setX(double dx){
x=dx;
}
double CPoint::getX(void){
return x;
}
void CPoint::setY(double dy){
y=dy;
}
double CPoint::getY(void){
return y;
}
// 线段类
class CLine{
// https://blog.csdn.net/acktomas/article/details/115550704
public:
CPoint start; // 起始点
CPoint end; // 结束点
CLine();
CLine(CPoint c1,CPoint c2);
double getLength(void);
};
CLine::CLine(){
}
CLine::CLine(CPoint c1,CPoint c2){
start=c1;
end=c2;
}
// 计算线段的长度
double CLine::getLength(void){
// https://blog.csdn.net/u010412858/article/details/82633359
double length = sqrt( pow((end.getX()-start.getX()) ,2) + pow((end.getY()-start.getY()),2) );
return length;
}
int main(void){
double x,y;
cout<<"请输入线段起始坐标:";
cin>>x>>y;
CPoint c1(x,y);
cout<<"请输入线段终点坐标:";
cin>>x>>y;
CPoint c2(x,y);
CLine c(c1,c2);
// https://www.99cankao.com/analytical/distance.php
cout<<"线段的长度为:"<<c.getLength()<<endl;
return 0;
}
问题解答:
要实现计算线段长度,可以定义一个点类和一个线段类,其中线段类中包含两个点的对象作为成员变量,通过两个点的坐标计算两点之间的距离即为线段的长度。
具体步骤如下:
class Point {
public:
Point(double x, double y): m_x(x), m_y(y) {}
double x() const { return m_x; }
double y() const { return m_y; }
private:
double m_x, m_y;
};
class Line {
public:
Line(const Point& p1, const Point& p2): m_p1(p1), m_p2(p2) {}
double length() const {
double dx = m_p1.x() - m_p2.x();
double dy = m_p1.y() - m_p2.y();
return sqrt(dx * dx + dy * dy);
}
private:
Point m_p1, m_p2;
};
int main() {
Point p1(0, 0);
Point p2(3, 4);
Line line(p1, p2);
std::cout << "line length: " << line.length() << std::endl;
return 0;
}
输出结果为:line length: 5
通过组合的方式,我们可以将点类和线段类组合起来,实现计算线段长度的功能。其中,点类可以在其他需要使用坐标的类中重用,达到代码重用的目的。