初学C++的时候对运算符重载的参数问题一直很迷惑,为什么有时候IDE提示参数过多呢?实际上运算符重载有两种形式:重载为成员变量和重载为友函数的形式。
- 重载为成员变量:
即将重载函数作为类的成员变量去定义。这时候函数有一个是隐含的参数this,就是说自动传入了一个类变量(重载函数好像比正常情况下少一个参数),这时重载函数中可以去访问类中任何字段。在系统编译时会这样调用重载函数 op1.operator+(op2);以下给出一个经典例子:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(){ real = 0; imag = 0; }
Complex(double r, double i){ real = r; imag = i; }
Complex operator + (Complex &c2);
void display();
private:
double real;
double imag;
};
Complex Complex::operator + (Complex &c2)
{
return Complex(Complex::real + c2.real, imag + c2.imag);
}
void Complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
Complex c1(3, 4), c2(5, -10), c3;
c3 = c1 + c2;
cout << "c1+c2 ="; c3.display();
}
- 重载为友函数:
如何重载为友函数,那就不会默认传入this参数,必须传入和原函数相同数量的参数,因为重载运算符不能改变原有运算符的操作个数。