【C++语法地图】+ 运算符重载

概念:对已有的运算重新进行定义,赋予其另一种功能,用于适应不同的数据类型

加号运算符重载

重载意义:可以实现两个自定义数据类型的相加运算

#include<iostream>
using namespace std;
int main(){
	int a = 10;
	int b = 20;
	int c = a + b;  
}

如上图,对于内置数据类型,编译器本来就知道如何运算,但是对于非内置的数据类型混合运算,就需要人为定义运算法则


成员函数重载+运算符

class Cat{
public:
  int age;
  int speed;
}:
int main(){
	Cat c1;
	c1.age = 10;
	c1.speed = 20;
	Cat c2;
	c2.age = 20;
	c2.speed = 30;
	Cat c3 = c1 + c2;
}

上图中欲实现两个Cat类对象的成员数据相加,可以编写一个成员函数,通过调用成员函数实现相加

Cat CatAddCat(Cat &p){//Cat类的成员函数
	Cat temp;
  	temp.age = this->age + p.age;
  	temp.speed = this->speed + p.speed;
  	return temp;
}

对此,编译器提供了一个通用名称——运算符重载函数名   即operator+

通过成员函数来重载+运算符,将下列程序编写在类的成员里

Cat operator+(Cat &p){//成员函数重载+运算符,仅仅是把函数名变成了operator+
	Cat temp;
  	temp.age = this->age + p.age;
  	temp.speed = this->speed + p.speed;
  	return temp;
}

成员函数重载的本质即  Cat c3 = c1.operator+(c2);

编译器帮忙简化为了  Cat c3 = c1 + c2;

Sample:

#include <iostream>
using namespace std;
class Cat{
public:
  int age;
  int speed;
};
Cat operator+(Cat &p){//成员函数重载+运算符,仅仅是把函数名变成了operator+
  Cat temp;
  temp.age = this->age + p.age;
  temp.speed = this->speed + p.speed;
  return temp;
}   

int main(){
	Cat c1;
	c1.age = 10;
	c1.speed = 20;
	Cat c2;
	c2.age = 20;
	c2.speed = 30;
	Cat c3 = c1 + c2;
}


全局函数重载+运算符

由于使用全局函数,无法使用与对象相关的this指针来指代其中一个变

量,所以传入的参数必须包含所有相加的对象

Cat operator+(Cat &p1,Cat &p2){//全局函数重载,传入全部需相加的变量
	Cat temp;
  	temp.age = p1.age + p2.age;
  	temp.speed = p1.speed + p2.speed;
  	return temp;
}

全局函数重载的本质是   Cat c3 = operator+( c1 , c2 );

编译器使得它简化为 Cat c3 = c1 + c2;

Sample:

#include<iostream>
using namespace std;
class Cat {
public:
	int age;
	int speed;
};
Cat operator+(Cat& p1, Cat& p2) {
	Cat temp;
	temp.age = p1.age + p2.age;
	temp.speed = p1.speed + p2.speed;
	return temp;
}
int main() {
	Cat c1;
	c1.age = 10;
	c1.speed = 20;
	Cat c2;
	c2.age = 20;
	c2.speed = 30;
	Cat c3 = c1 + c2;
	cout << c3.age << "  " << c3.speed;
}
  • +-*/运算的重载方式都是一样的,只需要在函数体内修改下就可以了

illustration:封面   by   紺屋鴉江  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值