c++——类 运算符重载

//运算符重载
//重写的规则需要满足运算符本身的规则
    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;
    }

 

 

    //字符串的输入输出重载
    ostream & operator << (ostream & os, CMyStr const& str)
    {
        os << str.pStr << '\n';
        return os;
    }

    istream & operator >> (istream & is, CMyStr & str)
    {
        char * tempStr = new char[10240];
        is >> tempStr;
        if (str.pStr)
        {
            delete[]str.pStr;
            str.pStr = NULL;
        }
        str.strcpy(tempStr);
        delete[]tempStr;
        return is;
    }

 

posted @ 2017-10-01 21:01  千面鬼手大人  阅读(513)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css