kurero
於旖
2019-05-09 19:38

求大神。内容:C++程序设计:运算符重载

  • c++
#include<iostream.h>
//using namespace std;
class Tpoint{
private:int x,y;
public:
    /*Tpoint(){
       x=1;
       y=1;
       cout<<"default constructor"<<endl;
    }*/
    Tpoint(int a=0,int b=0){
       x=a;y=b;
       cout<<"constructor,x="<<x<<"y="<<y<<endl;
    }
    Tpoint(const Tpoint&c ) {
        x = c.x;
        y = c.y;
        cout<<"copy constructor,x="<<x<<"y="<<y<<endl;
    }
    ~Tpoint(){
    cout<<"delete,x="<<x<<"y="<<y<<endl;
    }
    Tpoint operator+(const Tpoint& p){
        Tpoint temp;
        temp.x=x+p.x;
        temp.y=y+p.y;
        return temp;
    }
    Tpoint operator++(int){
        Tpoint before(x,y);
        x++;
        y++;
        return before;
    }
    Tpoint operator++(){
        x++;
        y++;
        return *this;
    }
    bool operator==(const Tpoint& p){
        if((x==p.x)&&(y==p.y))
            return 1;
        else 
            return 0;
    }
friend Tpoint operator-(Tpoint &p,Tpoint &q);
friend Tpoint operator--(Tpoint &p);
friend Tpoint operator--(Tpoint &p,int);
friend ostream& operator<<(ostream &out,Tpoint &p);
friend istream operator>>(istream &in,Tpoint &p);
};
Tpoint operator-(Tpoint &p,Tpoint &q)
{
    Tpoint temp;
    temp.x=p.x-q.x;
    temp.y=p.y-q.y;
    return temp;
}
Tpoint operator--(Tpoint &p)
{
    p.x--;
    p.y--;
    return p;
}
Tpoint operator--(Tpoint &p,int)
{
    Tpoint before(p.x,p.y);
    p.x--;
    p.y--;
    return before;
}
ostream& operator<<(ostream &out,Tpoint &p)
{
    out<<"("<<p.x<<","<<p.y<<")"<<endl;
    return out;
}
void main(){
    Tpoint p1(1,1),p2(3);
    Tpoint p3=p1+p2;
    cout<<(p1==p2)<<endl;
    cout<<p1<<endl;
    ++p1;
    --p1;
    Tpoint p4=p1-p2;

}

图片说明

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答