c++——类 运算符重载

C++运算符重载详解
本文详细介绍了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;
    }

 

转载于:https://www.cnblogs.com/ming-michelle/p/7617822.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值