3

运算符重载如何与函数重载结合使用。我的意思是我不太明白如何使用已经重载的函数来重载运算符。

4

1 回答 1

0

Operator is just a funky name given to infix functions (the ones written between their arguments). So, 1 + 2 is just a +(1, 2). Overloading means that you define several functions (or operators, which are the same thing) like this:

int square(int x);
double square(double x);

int operator + (int x, int y);
double operator + (double x, double y); // *

When these get called somewhere else, C++ determines which one to call not only by name, but also by the types of the actual arguments. So when you write square(5) the first one gets called and when you write square(5.0) the second one does. Beware that in more complex cases overload resolution (determining which function to call) is much more tricky.

Possibly you mean the situation, when your operator is overloaded not as a function, but as a method (i.e. it's first argument is passed using thiscall), and you'd like to overload a binary operator on it's second argument. Here's how it's done.

(*) Actually, you cannot declare operator + for int and double, because these are built in into a compiler.

于 2013-10-22T00:55:34.347 回答