0
点赞
收藏
分享

微信扫一扫

Point类

爱上流星雨 2022-03-11 阅读 62
c++

//编写Point类,重载+=和-=运算符,能够完成p1+=p2和p1-=p2的功能。
//【输入形式】int ,int
//【输出形式】
//【样例输入】1 2 3 4
//【样例输出】 p1=(1,2)
//             p2=(3,4)
//             p3=(4,6)
//             p4=(-2,-2)
#include <iostream>
using namespace std;
class Point
{
  public:
    double x;
    double y;
    Point();//构造函数
    friend Point operator+=(Point &a,Point &b);//重载+=运算符
    friend Point operator-=(Point &a,Point &b);//重载-=运算符
    friend istream& operator>>(istream&in,Point &a);//重载流插入运算符
    friend ostream& operator<<(ostream&out,Point &a);//重载流提取运算符
};
Point::Point()
{
    x=0;
    y=0;
}
Point operator+=(Point &a,Point &b)
{
    a.x+=b.x;
    a.y+=b.y;
    return a;
}
Point operator-=(Point &a,Point &b)
{
    a.x-=b.x;
    a.y-=b.y;
    return a;
}
istream& operator>>(istream&in,Point &a)
{
    in>>a.x>>a.y;
    return in;
}
ostream& operator<<(ostream&out,Point &a)
{
    out<<"("<<a.x<<","<<a.y<<")"<<endl;
    return out;
}
int main()
{
    Point p1,p2,p3,p4;//新建Point类对象p1,p2,p3,p4
    int p1x,p1y,p2x,p2y;//建立临时变量
    cin>>p1>>p2;//输入p1,p2
     cout<<"p1="<<p1;
      cout<<"p2="<<p2;//输出p1,p2
    p1x=p1.x;
    p1y=p1.y;
    p2x=p2.x;
    p2y=p2.y;
    p1+=p2;
    p3=p1;//赋值p3
    cout<<"p3="<<p3;//输出p3
    p1.x=p1x;
    p1.y=p1y;//还原p1
    p1-=p2;
    p4=p1;//赋值p4
     cout<<"p4="<<p4;//输出p4
}

举报

相关推荐

0 条评论