C++ Specific —>
type operator operator-symbol ( parameter-list )
The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
Rules of Operator Overloading
+ | - | * | / | % | ^ |
! | = | < | > | += | –= |
^= | &= | |= | << | >> | <<= |
<= | >= | && | || | ++ | –– |
( ) | [ ] | new | delete | & | | |
~ | *= | /= | %= | >>= | == |
!= | , | –> | –>* |
Restrictions on Operator Overloading
. | .* | :: | ?: |
For more information, see C/C++ Operators and Operator Precedence Table.
END C++ Specific
Example
The following example overloads the + operator to add two complex numbers and returns the result.
// Example of the operator keyword
class Complex
{
public:
Complex( float re, float im );
Complex operator+( Complex &other );
friend Complex operator+( int first, Complex &second );
private:
float real, imag;
};
// Operator overloaded using a member function
Complex Complex::operator+( Complex &other )
{
return Complex( real + other.real, imag + other.imag );
};
// Operator overloaded using a friend function
Complex operator+( int first, Complex &second )
{
return Complex( first + second.real, second.imag );
}