设计一个用来表示直角坐标系的Location类,在主程序中创建类Location的两个对象A和B,要求A的坐标点在第3象限,B的坐标点在第2象限,分别采用成员函数和友元函数计算给定两个坐标点之间的距离,要求按如下格式输出结果:
A(x1,y1), B(x2,y2),
Distance1=d1
Distance2=d2
其中:x1、y1、x2、y2为指定坐标值,d1和d2为两个坐标点之间的距离。
#include<iostream>
#include<cmath>
using namespace std;
class Location{
public:
Location(double a ,double b);//构造函数
double getx();//成员函数,取x坐标值
double gety();//成员函数,取y坐标值
double distance(Location&d);//成员函数,求给定两点之间的距离
friend double distance1(Location&,Location&);//友元函数,求给定两点之间
private:
double x,y;
};
Location::Location(double a,double b)//构造函数的定义;
{ x=a;
y=b;
}
double Location:: getx()//输出x;
{ return x;
}
double Location:: gety()//输出y;
{ return y;
}
double Location::distance(Location&d)
{ double d1;
d1=sqrt((this->x-d.x)*(this->x-d.x)+(this->y-d.y)*(this->y-d.y));
//this指针是包含在每一个成员函数中的一个特殊指针,它是指向本类对象的一个指针,
//它的值未被调用的成员函数所在对象的地址,在这里可以写成A.x,A.y;
cout<<"Distance1="<<d1<<endl;
return 0;
}
double distance1(Location& c,Location& d)
{ double d2;
d2=sqrt((c.x-d.x)*(c.x-d.x)+(c.y-d.y)*(c.y-d.y));
cout<<"Distance2="<<d2<<endl;
return 0;
}
int main()
{
Location A(-1,-1);
Location B(-1,1);
cout<<"A("<<A.getx()<<","<<A.gety()<<") , B("<<B.getx()<<","<<B.gety()<<")"<<endl;
A.distance(B);
distance1(A,B);
return 0;
}