在类内重载操作符适合,只能提供给操作符一个参数。
如下定义就会报错。
struct Rational
{
public:
Rational operator*(const Rational& lhs, const Rational& rhs)
{...}
private:
int numerator;
int deminator;
};
因为*法运算符是双目运算符,所以不能超过2个参数
Rational operator*(const Rational& lhs, const Rational& rhs)
这里是放在类成员中的运算符重载,所以你要把默认的this指针算上去。这句话对于编译器来说,其实是
Rational operator*(const Rational& lhs, const Rational& rhs)
那么可以将原来的写成
struct Rational
{
public:
Rational operator*(const Rational& rhs)
{...}
private:
int numerator;
int deminator;
};
或者把运算符重载写成友元函数,放到全局中,那么就可以写成 Complex operator+ (Complex & c1, Complex& c2); 这样了。又或者直接在类外定义操作符为全局函数。