概念:对已有的运算重新进行定义,赋予其另一种功能,用于适应不同的数据类型
加号运算符重载
重载意义:可以实现两个自定义数据类型的相加运算
#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 紺屋鴉江