运算符重载
例如有一个类MyTime,需要对这个类对象做操作,例如两个时间相加
MyTime operator+(const MyTime & t) const{
MyTime sum;
结果存在sum中
}
这行代码就是声明MyTime这个类运算符重载函数的
最左边是类名, operator+表示是加法运算符重载方法,括号中const表示传进来的不能修改,最后面的const表示当前类的变量不能修改
另外还有 += 的操作符,就是讲结果赋给当前类中
我们还可以把传进来的MyTime对象改为一个整数
time + 20;
这个和 time1 + time2 一样
但是如果改一下顺序变成 20 + time,就不行了
#include<iostream>
using namespace std;
class Complex{
public:
Complex(int a, int b){
this->a = a;
this->b = b;
}
Complex operator+(Complex &c1){
Complex c3(this->a + c1.a, this->b + c1.b);
return c3;
}
void printComplex(){
cout << "(" << this->a << "," << this->b << "i" << ")" << endl;
}
private:
int a;
int b;
};
int main(){
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2;
c3 = operator+(c1, c2); //这样也行
c3.printComplex();
}
双目运算符重载 +=或者++这种
和单目运算一样