🤣来了🤣
😂来个小题😂
编程实现:
1、定义一个线段类(Line
),具体要求如下:
(1)Line
类使用Point
类对象定义线段的两个端点值。
(2)为Line
类增加有参构造函数Line
,使得调用该构造函数时可以初始化两个端点值。
(3)Line
类中定义一个公有函数:length()
,表示两个端点的距离,它将返回double
类型的距离数据。
2、定义一个线段长度类(Line_length
),具体要求如下:
(1)Line_length
类使用Point
类对象定义线段的两个端点值。
(2)Line_length
类使用重载的构造函数调用Line
类返回double
类型的线段长度。
示例输出:
线段长度是:1
代码如下:
#include<iostream>
#include<cmath>
using namespace std;
class Point //坐标点类
{
public:
const double x,y;
Point(double x=0.0, double y=0.0): x(x),y(y) {}
double distanceTo(Point p)const //到指定点的距离
{
return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)) ;
}
};
class Line //线段类
{
public:
const Point p1,p2; //线段的两个端点
Line(Point p1, Point p2):p1(p1),p2(p2) {}
double length()const
{
return p1.distanceTo(p2); //线段的长度
}
};
class Line_length //线段长度类
{
public:
const Point p1,p2; //线段的两个顶点
Line_length(Point p1,Point p2):p1(p1),p2(p2) {}
double length()const //线段的长度
{
return Line(p1, p2).length() ;
}
};
int main()
{
Line_length L(Point(0.0, 0.0), Point(0.0, 1.0));
cout<<"线段长度是:"<<L.length()<<endl;
return 0;
}
小伙伴自行运行
白