文章目录
1 概述
程序员可以对C++中的+、=等运算符重新定义,以适应不同数据类型的计算。
运算符重载规则:
- 重载后的运算符不能改变原有运算符的运算规则(加号运算符不能重载为两个数相减)
- 不能定义原本没有的运算符
运算符重载语法:
retValue operator[+-*/...](param1, param2) {
}
使用operator关键字,后接要重载的运算符,其他的都是和普通函数定义相同。
2 常用运算符重载
2.1 加号运算符重载
#include <iostream>
using namespace std;
class TestClass {
public:
TestClass(){
};
TestClass(int a, int b):mA(a),mB(b){
};
TestClass operator+(const TestClass& TestClass) const {
class TestClass temp;
temp.mA = this->mA + TestClass.mA;
temp.mB = this->mB + TestClass.mB;
return temp;
}
public:
int mA;
int mB;
};
// TestClass operator+(const TestClass& testClass1, const TestClass& testClass2) {
// class TestClass temp;
// temp.mA = testClass1.mA + testClass2.mA;
// temp.mB = testClass1.mB + testClass2.mB;
// return temp;
// }
int main() {
TestClass testClass1(10,20);
TestClass testClass2(30,40);
TestClass testClass3 = testClass1 + testClass2;
cout << "testClass3.mA = " << testClass3.mA << endl;
cout << "testClass3.mB = " << testClass3.mB << endl;
return 0;
}
加法运算符重载,可以实现两个对象相加返回一个对象,而对象的哪些属性参与运算则由软件开发者自己定义。
可以通过全局函数实现,也可以通过成员函数实现。二者的区别是全局函数需要传入两个参数,而成员函数由于this指针的存在只需要传入一个参数。
需要注意的是这里的全局函数实现和成员函数实现不能同时存在,因为调用的时候会产生分歧,不知道应该调用成员函数还是全局函数。
2.2 左移运算符重载
通常输入输出操作都是通过流来实现,像cout、cin函数,就是重载了左移和右移运算符的,通常重写这两个运算符也是为了文件的输入输出操作。
#include <iostream>
using namespace std;
class TestClass {
friend ostream& operator<<(ostream& out, TestClass& testClass);
public:
TestClass() {
};
TestClass(int a, int b) : mA(a), mB(b) {
};
void operator<<(ostream &out) const {
out