C++学习笔记之运算符重载例子

本文重载前置--,后置--和运算符+。

代码如下:

#include <iostream>
using namespace std;

/**
 * 定义Coordinate类<span style="display: none; width: 0px; height: 0px;" id="transmark"></span>
 * 数据成员:m_iX,m_iY
 * 成员函数:构造函数
 * 重载--运算符,重载+运算符
 */
class Coordinate
{
public:
    Coordinate(int x, int y)
	{
		m_iX = x;
		m_iY = y;
	}
    // 前置--运算符重载
	Coordinate &operator--()
    {
        this->m_iX--;
        this->m_iY--;
        return *this;
    }
    
    
    
    // 后置--运算符重载
    Coordinate operator--(int)
    {
        Coordinate coor(*this);
        coor.m_iX=this->m_iX--;
        coor.m_iY=this->m_iY--;
        return coor;
    }
    
    
    
    // +号运算符重载
	Coordinate operator+(Coordinate &c)
    {
        Coordinate temp(0,0);
        temp.m_iX=this->m_iX+c.m_iX;
        temp.m_iY=this->m_iY+c.m_iY;
        return temp;
    }
    
    

public:
	int m_iX;
	int m_iY;
};

int main(void)
{
	Coordinate coor1(1, 3);
	Coordinate coor2(2, 4);
	Coordinate coor3(0, 0);

	coor1--;
	--coor2;
	coor3 = coor1 + coor2;

	cout << coor3.m_iX << endl;
	cout << coor3.m_iY << endl;

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值