1. 通过operator关键字可以利用函数扩展操作符
2. operator的本质是通过函数重载实现操作符重载
3. 应用于类中并且重载函数为全局函数时,要使用友元函数(关键字friend)
4. 当重载函数为类中的成员函数时, 不用friend并且少一个函数参数
注意点:
1. 当无法修改左操作数的类时, 使用全局函数进行重载
2. = [] () 和 -> 只能通过成员函数进行重载
例如:
#include <iostream>
using namespace std;
class S
{
public:
S(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
void getA(void)
{
cout<<a<<endl;
}
void getB(void)
{
cout<<b<<endl;
}
S operator +(const S& s2);
friend ostream& operator <<(ostream& out, const S& c);
private:
int a;
int b;
};
S S::operator +(const S& s2)
{
S ret;
ret.a = this->a + s2.a;
ret.b = this->b + s2.b;
return ret;
}
ostream& operator <<(ostream& out, const S& c)
{
out<<c.a<<" "<<"+"<<" "<<c.b<<"i";
}
int main(void)
{
S s3(1,2);
S s4(3,4);
S s5 = s3 + s4;
s5.getA();
s5.getB();
cout<<s5<<endl;
return 0;
}