operator+ 和 operator[] 有什么区别

what is different between operator+ and operator[]

我被我们课上的下面这句话搞糊涂了

By way of Functions of the Name operator@ the named operator @ (excluding = () [] ? : . -> .* ::) can be overloaded for datatypes that have not been 'built in'.

我意识到运算符 @ 指的是“+ - * / ^ ...等”之类的东西,并且我了解这些重载的方式和原因。但我对“(不包括 =()[]? : 。 -> .* ::)" 上面提到的部分。它是什么意思,为什么要排除这些运算符?

我是说我声明

something operator+(something a, something b)

而且我没有发现我声明的方式有什么大的不同

something operator[] (something c)

据说[]、()、->、=等只能用成员函数重载,但是我上面说的运算符+也只能用成员函数重载,不是吗?

有两种方法overload operators

  • 作为 "free" 函数(即非成员),在 class 之外,您要为其重载
  • 作为成员函数。

上面的 link 很好地阐明了 table 可以以成员函数的形式重载 =()[] , 和 -> 但作为自由函数被禁止。

此外,范围解析运算符 :: 以及成员访问 .、通过指向成员的指针访问成员 .*,以及三元条件运算符 x ? y : z cannot be overloaded 完全没有。


编辑: 这里有一个 exampleoperator* 定义为成员函数,operator+ 定义为非成员函数:

class Rational {
    int p; 
    int q; 
public:  
    Rational (int d=0, int n=1) : p{d}, q{n} { } 
    Rational operator*(const Rational& r) const {    // for curent object * r
        return Rational(p*r.p,q*r.q); 
    }
    int numerator() const {return p; }
    int denominator() const { return q; } 
}; 

Rational operator+(const Rational &a, const Rational &b) {   // for object a + object b
    return Rational(a.numerator()*b.denominator()+b.numerator()*a.denominator(),
                                                      a.denominator()*b.denominator());
}