//一般我们使用+-*/运算符都是数相加,但如果两个类相加怎么解决呢?使用引入运算符重载,运算符重载就是让+-*/可以用于其他相加,例如两个类相加
// 1、加法运算符
int a = 520;
int b = 1314;
cout << a + b << endl;
// 2、字符串拼接
string c = "520";
string d = "1314";
cout << c + d << endl;
string e = "我";
string f = "爱你";
cout << e + f << endl;
二.一般运算符重载
1.加号重载
#include <iostream>
using namespace std;
//实现重载的类
class Complex {
public:
Complex() : real(0), image(0) {
}
Complex(int real, int image) {
this->real = real;
this->image = image;
}
//一般我们都是使用函数实现a.add(b);
Complex add(Complex& other) {
Complex ret;
ret.real = this->real + other.real;
ret.image = this->image + other.image;
return ret;
}
//但使用重载后,可以直接c = a + b;简洁好看
//必须这样定义operator+,就不用operator+()这样调用函数了,直接a+b就行了
//而且它是显性的,必须定义operator+才能使用,要不然还是得用函数解决
Complex operator+(Complex& other) {
Complex ret;
ret.real = this->real + other.real;
ret.image = this->image + other.image;
return ret;
}
// a + bi
void Print() {
cout << real << '+' << image << 'i' << endl;
}
private:
int real;
int image;
};
int main() {
Complex a(10, 20);
Complex b(5, 8);
Complex c = a.add(b);//函数实现
Complex c = a + b;//运算符重载实现
Complex d = a - b;
c.Print();
d.Print();
return 0;
}
//==重载
bool operator==(const Point& other) const {
return m_x == other.m_x && m_y == other.m_y;
}
//<重载
bool operator<(const Point& other) const {
int d = m_x * m_x + m_y * m_y;
int otherd = other.m_x * other.m_x + other.m_y * other.m_y;
return d < otherd;
}
//>重载
bool operator>(const Point& other) const {
if (*this == other) {
return false;
}
if (*this < other) {
return false;
}
return true;
}
Point a(1, 6);
Point b(2, 5);
if (a == b) {
cout << "a 和 b 相等" << endl;
}
else if (a < b) {
cout << "a 比 b 更加接近原点" << endl;
}
else if(a > b) {
cout << "b 比 a 更加接近原点" << endl;
}
5.函数调用运算符重载
//函数调用运算符重载:就是用类当作函数使用
class AddFunctor {
public:
AddFunctor() {
m_acc = 0;
}
int operator() (int a, int b) {
m_acc++;
return a + b + m_acc;
}
private:
int m_acc;
};
AddFunctor add;//这个定义一个类
cout << add(5, 6) <<endl;//把类当作函数使用