C++中运算符重载(--,+,<<)


今天学习了c++中的运算符重载,记录如下:

1、前置单目运算符的重载

重载函数的声明为: 返回值 operator运算符(){函数实现},例如实现坐标类的自减运算:

Coordinate& operator--() {
    --m_iX;
    --m_iY;
    return *this;
}

其中&代表返回自身的引用,如果不加,返回的是一个对象。返回引用的好处是它可以进行多次运算,例如一个对象coor,--(--(coor));会执行两次自减,而返回对象则只执行一次。

2、后置单目运算符的重载

重载函数的声明为: 返回值 operator运算符(int){函数实现},注意其中参数为一个int,以区别前置单目运算。注意后置单目运算符是先返回值,再进行自减运算,因此需要一个临时类来储存并返回原来的对象。并且对this指向的对象进行自减运算

Coordinate operator--(int) {
	Coordinate temp(*this);
	this->m_iX--;
	this->m_iY--;
	return temp;
}

3、双目运算符重载

重载函数的声明为: 返回值 operator运算符(参数){函数实现},双目运算符如果声明为成员函数的话,只有一个参数,因为已有默认this参数指向调用的对象。

Coordinate operator+(Coordinate c) {
     this->m_iX += c.m_iX;
     this->m_iY += c.m_iY;
     return *this;
}

4、输出运算符<<重载


我在操作中发现<<重载声明为成员函数编译会报错C2804,operator的运算符函数的参数过多,我觉得是因为在类内声明的原因,于是把它声明为外部友元类,便可以有两个参数

friend ostream &operator<<(ostream &out,Coordinate c);

在类外定义为:

ostream & operator<<(ostream &out,Coordinate c)//注意ostream的&out是引用
{
	out <<"(" << c.m_iX << " , " << c.m_iY <<")"<< endl;
	return out;
}

完整的程序如下:

#include <iostream>
using namespace std;

class Coordinate
{
public:
	int m_iX;
	int m_iY;
public:
	Coordinate(int x, int y)
	{
		m_iX = x;
		m_iY = y;
	}
	// 前置--运算符重载
	Coordinate& operator--() {
		--m_iX;
		--m_iY;
		return *this;
	}

	// 后置--运算符重载
	Coordinate operator--(int) {
		Coordinate temp(*this);
		this->m_iX--;
		this->m_iY--;
		return temp;
	}

	// 双目+号运算符重载
	Coordinate operator+(Coordinate c) {
		this->m_iX += c.m_iX;
		this->m_iY += c.m_iY;
		return *this;
	}

	//输出运算符<<重载
	friend ostream &operator<<(ostream &out,Coordinate c);
};
ostream & operator<<(ostream &out,Coordinate c)//注意ostream的&out是引用
{
	out <<"(" << c.m_iX << " , " << c.m_iY <<")"<< endl;
	return out;
}

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

	--(--coor1);//重载前置--
	coor2--;//重载后置--
	coor3 = coor1 + coor2;//重载+

	cout << coor1;//重载<<

	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、付费专栏及课程。

余额充值