运算符重载作用
对已有的运算符重新进行定义,赋予其另外一种功能,以适应不同的数据类型,作用:实现两个自定义的数据类型相加的运算
运算符重载的本质
运算符重载其实就是定义一个函数,在函数体内实现想要的功能,当用到该运算符时,编译器会自动调用这个函数。也就是说,运算符重载是通过函数实现的,它本质上是函数重载。
语法
返回值类型 operator 运算符名称 (形参表列){
//TODO:
}
operator是关键字,专门用于定义重载运算符的函数,和运算符一起构成函数名
加号运算符重载
例:将两个对象的某些属性对应相加
#include<iostream>
using namespace std;
class Person
{
public:
int m_a;
int m_b;
//成员函数重载的本质调用
Person operator+(Person& p)
{
Person temp;
temp.m_a = this->m_a + p.m_a;
temp.m_b = this->m_b + p.m_b;
return temp;
}
Person operator+(int num) //在此处进行运算符重载,关键字operator+运算符
{
Person temp;
temp.m_a = this->m_a + num;
temp.m_b = this->m_b + num;
return temp;
}
};
//全局函数重载
//成员函数重载的本质调用
//Person operator+(Person& p1,Person& p2)
//{
// Person temp;
// temp.m_a = p1.m_a + p2.m_a;
// temp.m_b =p1.m_b + p2.m_b;
// return temp;
//}
void test01()
{
Person p1;
Person p2;
Person p3;
p1.m_a = 10;
p1.m_b = 10;
p2.m_a = 10;
p2.m_b = 10;
p3 = p1 + p2; //本质:p3 = p1 operator+(p2)
cout << p3.m_a<< endl;
cout << p3.m_b << endl;
//运算符重载也可以发生函数重载
p3 = p1 + 100; //原型:Person operator+(int num)
}
int main()
{
test01();
return 0;
}
注意
- 不是所有的运算符都可以重载,长度运算符sizeof、条件运算符: ?、成员选择符.和域解析运算符::不能被重载
- 运算符重载不改变运算符的优先级和结合性
- 运算符重载函数不能有默认的参数,否则就改变了运算符操作数的个数
- 运算符重载函数既可以作为类的成员函数,也可以作为全局函数
- 箭头运算符->、下标运算符[ ]、函数调用运算符( )、赋值运算符=只能以成员函数的形式重载