实验要求:
自定义如下形式的一个称为point 的类,其对象表示平面上的一个点(x,y),并通过类成员方式对该类重载二目运算符“+”和“^”,用来求出两个对象的和以及两个对象(平面点)的距离。各运算符的使用含义(运算结果)如下所示:
(1.2, -3.5) + (-1.5, 6) = (-0.3, 2.5);
(1.2, -3.5) ^ (-1.5, 6) = 9.87623。
编写主函数,说明类对象,而后通过类对象实现所定义的相关运算(以验证其正确性)。
class point {
double x,y;
public:
point (double x0=0, double y0=0) {x=x0; y=y0;}
point operator + (point pt2);
double operator ^ (point pt2);
void display();
};
二、实验过程(实验步骤、记录、数据、)
#include
#include
class Point
{
double x,y;
public:
Point (double x=0, double y=0) {}
Point operator + (Point &pt2);
double operator ^ (Point &pt2);
friend ostream &operator <<(ostream &,Point &);
friend istream &operator >>(istream &,Point &);
void display();
};
int main()
{
Point p1,p2,p3;
double b;
cout<<"请输入Q1的坐标"<<endl;
cin>>p2;cout<<"请输入Q2的坐标"<<endl;cin>>p3;
p1=p3+p2;
b=p3^p2;
cout<<endl<<"Q1,Q2之间的和:"<<p1<<"="<<p2<<"+"<<p3<<endl;
cout<<"Q1,Q2之间的距离:"<<b<<"="<<p1<<"^"<<p2<<endl;
return 0;
}
ostream &operator <<(ostream &output,Point &p1)
{
output<<"("<<p1.x<<","<<p1.y<<")";
return output;
}
istream &operator >>(istream &input,Point &p1)
{
input>>p1.x>>p1.y;
return input;
}
Point Point::operator + (Point &pt2)
{
Point p;
p.x=pt2.x+x;
p.y=pt2.y+y;
return p;
}
double Point::operator ^ (Point &pt2)
{
return sqrt((pt2.x-x)*(pt2.x-x)+(pt2.y-y)*(pt2.y-y));
}
3、运行结果: