例:已知坐标的两点,求距离。
#include<iostream.h>
#include<math.h>
class Point //点
{
double x,y;
public:
Point(double xx,double yy) //构造函数
{
x=xx;
y=yy;
}
Point(Point &p) //拷贝构造函数,可不写,系统会自动创建。
{
x=p.x;
y=p.y;
}
double GetX(){return x;} //得到点x坐标
double GetY(){return y;} //得到y坐标
};
class Distance //距离
{
Point p1,p2;
double dist;
public:
Distance(Point a,Point b);
double GetDis(){return dist;}
};
Distance::Distance(Point a,Point b):p1(a),p2(b)
{ //构造函数求距离,其中a赋给p1,b赋给p2用了拷贝构造函数
double x=double(p1.GetX()-p2.GetX());
double y=double(p1.GetY()-p2.GetY());
dist=sqrt(x*x+y*y);
}
void main()
{
double a1,b1,a2,b2;
cout<<"Please input the first point:\n";
cin>>a1>>b1;
Point myp1(a1,b1); //第一个点
cout<<"Please input the second point:\n";
cin>>a2>>b2;
Point myp2(a2,b2); //第二个点
cout<<"The distance is:\n";
Distance myd(myp1,myp2); //将myp1,myp2赋给形参a,b用了拷贝构造函数
cout<<myd.GetDis()<<endl;
}