码迷,mamicode.com
首页 > 编程语言 > 详细

c++——类 运算符重载

时间:2017-10-01 22:06:45      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:重载   opera   产生   赋值   输入输出   return   nbsp   ppt   str   

//运算符重载
//重写的规则需要满足运算符本身的规则
    class CMyPoint
    {
        int x, y;
        public:
        CMyPoint();
        CMyPoint(int x, int y);
        ~CMyPoint();

        CMyPoint operator+(CMyPoint const& pt) const;//是不能修改this的值
        friend CMyPoint operator-(CMyPoint const&p1, CMyPoint const & p2);

        CMyPoint& operator++(); //前置,因为是自己,所以要加上&
        CMyPoint operator++(int);//++后置,int是标识符 不使用& 是因为,先赋值在运算,赋值是产生一个临时变量先

        friend ostream& operator<<(ostream& os, CMyPoint const& pt);//friend 因为在输入输出时,第一个参数不是this,而是输入输出流
        friend istream& operator>>(istream& is, CMyPoint &pt);
        };
        CMyPoint CMyPoint::operator+(CMyPoint const& pt) const
        {
        CMyPoint tempPt;
        tempPt.x = this->x + pt.x;
        tempPt.y = this->y + pt.y;
        return tempPt;
    }

    MyVector operator-( MyVector i, MyVector j)
    {
    return  MyVector(i.x-j.x, i.y-j.y);
    }

    CMyPoint& CMyPoint::operator++()
    {
        (*this).x++;
        this->y++;
        return *this;
    }

    CMyPoint CMyPoint::operator++(int)
    {
        CMyPoint tempPt = *this;
        this->x++;
        this->y++;
        return tempPt;
    }

    ostream& operator<<(ostream& os, CMyPoint const& pt)
    {
        os << pt.x << \t << pt.y << endl;
        return os;
    }

    istream& operator>>(istream& is, CMyPoint &pt)
    {
        is >> pt.x;
        is >> pt.y;
        return is;
    }

    CMyPoint operator-(CMyPoint const& p1, CMyPoint const& p2)
    {
        CMyPoint tempPt;
        tempPt.x = p1.x - p2.x;
        tempPt.y = p1.y - p2.y;
        return tempPt;
    }

 

c++——类 运算符重载

标签:重载   opera   产生   赋值   输入输出   return   nbsp   ppt   str   

原文地址:http://www.cnblogs.com/ming-michelle/p/7617822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!