c++ 运算符重载

在c++中,运算符的操作对象可以是基本的数据类型,也可以是类中重新定义的运算符,赋予运算符新的功能,对类对象进行相关操作

c++运算符重载的语法

返回值类型 operator运算符名称 (参数列表){
    ...
}

c++ 重载+,- 运算符

运算符重载可以用成员函数重载,也可以使用全局函数重载,下面进行介绍

class Coordinate {
public:
	int x;
	int y;
public:
	Coordinate();
	Coordinate(int x, int y);
	Coordinate& operator+(Coordinate& cdt);
};
Coordinate& Coordinate::operator+(Coordinate& cdt) {
	Coordinate cdt1;
	cdt1.x = x + cdt.x;
	cdt1.y = y + cdt.y;
	return cdt1;
}

 通过成员函数重载,我们只需传入一个对象作为形参,另外一个对象进行调用operator+()方法便可实现两个对象的成员变量值进行相加。其中

cdt3 = cdt1 + cdt2;

相当于

cdt3 = cdt1.operator+(cdt2);

其实没那么想的那么复杂,就是重新定义了operator+()方法,然后进行调用即可

再来看一下全局函数是怎么实现的

全局函数我们需要两个对象进行操作,故我们需要传入两个对象作为形参传入函数,然后对其进行操作

Coordinate& operator-(Coordinate& cdt1, Coordinate& cdt2) {
	Coordinate cdt3;
	cdt3.x = cdt1.x - cdt2.x;
	cdt3.y = cdt1.y - cdt2.y;
	return cdt3;
}

这里逻辑是一样的,重载乘除也是照葫芦画瓢

####################################################################

重载==,-运算符

class Coordinate {
public:
	int x;
	int y;
public:
	Coordinate();
	Coordinate(int x, int y);
	bool operator==(Coordinate& cdt);
	bool operator<(Coordinate& cdt);
};
bool Coordinate::operator==(Coordinate& cdt) {
	return x == cdt.x;
}
bool Coordinate::operator<(Coordinate& cdt) {
	return x < cdt.x;
}
int main() {
	Coordinate cdt1(20, 20);
	Coordinate cdt2(10, 10);
	bool b = cdt2 == cdt1;
	cout << "坐标x值是否相等:" << b << endl;
	b = cdt2 < cdt1;
	cout << "cdt2坐标x值是否大于cdt1坐标x值:" <<b<<endl;
}

 这里写的比较简单,其实逻辑都差不多。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值