c++初级 之 运算符重载

一般在需要对类的成员进行运算符操作时进行运算符重载。运算符重载有两种方式:1.定义为类的友元函数2.定义为类的成员函数。

以下为例:

demo.cpp

#include<iostream>
#include<stdlib.h>
#include<string>
#include"Coordinate.h"
using namespace std;


Coordinate& operator++(Coordinate& coor);
ostream& operator << (ostream& out,const Coordinate &coor);

int main()
{
	try{   //try和catch一般只能放在main函数里用,异常可以在类、其他函数等不同地方抛出throw
	Coordinate c(1,3);
	cout << (c++).getX() << endl;//如果用的是返回引用的那個重载,那这里会打印出乱码
	cout << c++ << endl;
	Coordinate test = (c++);
	cout << test << endl;
	cout << (++c).getX() << endl;
	cout << (test + c) << endl;
	cout << c << endl;
	int i = 0;
	int j = (i++); //充分理解后置++,不管打不打括号,都是返回的原值,后再++,所以这里j还是 = 0
	cout << j << endl;
	c[0] = 0;
	cout << c[0] << endl;
	}
	catch(string &e){
		cout << e << endl;
	} 
	system("pause");
	return 0;

}

Coordinate& operator++(Coordinate& coor)
{
	coor.m_iX++;
	coor.m_iY++;
	return coor;
}

ostream& operator << (ostream& out,const Coordinate &coor)
{
	out << coor.m_iX << "," << coor.m_iY;
	return out;
}

点类Coordinate.h


#include<iostream>//因为用到了ostream类对象的引用,所以要包含这个头文件
using namespace std;

class Coordinate
{
	//friend int& operator[](Coordinate &coor,int index);按理讲也是可以的,但是为了方便起见,c++规定,[]运算符重载只能是类的成员函数
	friend Coordinate& operator++(Coordinate& coor);//前置++
	friend ostream& operator<<(ostream& out,const Coordinate &coor);//无法用类的成员函数定义,因为类的成员函数实质上的第一个参数是this指针,然而<<的第一个参数是指运算符左边的变量,应该是个ostream类对象,而非this指针所指的Coordinate类对象.因为二元运算符中的调用格式是 参数一 运算符 参数二
public:
	Coordinate(int x,int y);
	int& operator[](int index);//必须返回引用,否则返回的只是一个不能修改的量,无法实现c[0] = 0类似的功能。但int型的参数index不能是引用类型,因为传入的可能是常量0、1,常量并非引用变量
	Coordinate operator++(int);//有int类型参数,表示是后置++
	Coordinate operator+(const Coordinate & coor);//加const则coor无法改变
	//Coordinate& operator++(int);不能用&,否则当后置++函数被调用结束后,临时变量被释放,返回的引用的值就会是乱码
	//总结就是如果返回的是临时变量,那就只能返回对象,否则尽量返回指针
	int getX();


private:
	int m_iX,m_iY;
};

具体Coordinate.cpp


#include"Coordinate.h"
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;

Coordinate::Coordinate(int x,int y):m_iX(x),m_iY(y)
{
}
Coordinate Coordinate::operator++(int)
{
	Coordinate c = *this;
	m_iX++;
	m_iY++;
	return c;
}
int Coordinate::getX()
{
	return m_iX;
}

Coordinate Coordinate::operator+(const Coordinate & coor)
{
	Coordinate sum(0,0);
	sum.m_iX = m_iX + coor.m_iX;
	sum.m_iY = this->m_iY + coor.m_iY;
	return sum;
}

int& Coordinate::operator[](int index)
{
		if(index == 0)return m_iX;
		if(index == 1)return m_iY;
		throw string("脚标只能是0或1。");
}

运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值