美文网首页
C++学习第10课,类内运算符重载

C++学习第10课,类内运算符重载

作者: Mr小熊_1da7 | 来源:发表于2019-06-16 17:59 被阅读0次

    1 先上代码


    #include <iostream>

    #include <string.h>

    #include <unistd.h>

    using namespace std;

    class Point {

    private:

    int x;

    int y;

    public:

    Point()

    {

    cout<<"Point()"<<endl;

    }

    Point(int x, int y) : x(x), y(y)

    {

    cout<<"Point(x,y)"<<endl;

    }

    Point(const Point &per)

    {

    cout<<"Point(copy)"<<endl;

    x = per.x;

    y = per.y;

    }

    ~Point()

    {

    cout<<"~Point()"<<endl;

    }

    int getX(){ return x; }

    int getY(){ return y; }

    void setX(int x){ this->x = x; }

    void setY(int y){ this->y = y; }

    void printInfo()

    {

    cout<<"("<<x<<", "<<y<<")"<<endl;

    }

    /*+加法*/

    Point operator+(Point &a)

    {

    Point n;

    n.x = this->x+a.x;

    n.y = this->y+a.y;

    cout<<"operator+(Point &a)"<<endl;

    return n;

    }

    Point operator++(int b)

    {

    Point n;

    n.x = this->x++;

    n.y = this->y++;

    cout<<"p++"<<endl;

    return n;

    }

    Point& operator++(void)

    {

    this->x++;

    this->y++;

    cout<<"++p"<<endl;

    return *this;

    }

    friend ostream& operator<<(ostream& cout, Point &a);

    };

    /*这里是<<*/

    ostream& operator<<(ostream& cout, Point &a)

    {

    cout<<"("<<a.x<<", "<<a.y<<")";

    return cout;

    }

    int main(int argc, char **argv)

    {

    cout<<"*******************"<<endl;

    Point p1(1, 2);

    Point p2(2, 3);

    cout<<"*******************"<<endl;

    Point m1 = p1+p2;

    Point m2 = p1++;

    Point m3 = ++p1;

    cout<<"*******************"<<endl;

    cout <<"Port = "<<p1<<endl;

    return 0;

    }



    自己看

    相关文章

      网友评论

          本文标题:C++学习第10课,类内运算符重载

          本文链接:https://www.haomeiwen.com/subject/jurxfctx.html