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 に答える