重载的运算符是具有特殊名字的函数:它们的名字由关键字operator和其后要定义的运算符号共同组成。
和其他函数一样,重载的运算符也包含返回类型、参数列表以及函数体。
重载运算符函数的参数数量于该运算符作用的运算对象数量一样多。
当一个重载的运算符是成员函数时,this绑定到左侧运算对象。成员运算符函数的(显式)参数数量比运算对象的数量少一个。
class Student
{
public:
double real, imag;
Student(double r,double i):real(r),imag(i){}
Student operator+(const Student& other)
{
return Student(real + other.real, imag + other.imag);
}
};
Student operator+(const Student& d1, const Student& d2)
{
return Student(d1.real + d2.real+3.5, d1.imag + d2.imag);
}
int main()
{
Student a(1.0, 2.0);
Student b(7.0, 5.0);
Student c = a + b;// 等价于 a.operator+(b)
cout << c.real << endl;
}
如上面的代码所示,+运算符一般有两个参数,在成员函数中,左侧的 a 是通过 this 隐式传递的
1427

被折叠的 条评论
为什么被折叠?



