operators
Contents | 
[edit] Operator Overloading
[edit] Syntax
| type operator op ( params ) ; | |||||||||
[edit] Explanation
- <type> is/are the type(s) of the variables.
 - <op> is the particular operator (e.g. +, +=, <<, >>, &&, ||, %, etc.).
 - <params> is/are the name(s) of the required parameters (depends on the operator).
 
[edit] Restrictions
- You cannot create new operators such as ** or &|.
 - Not all operators can be overloaded
 - Some operators can only be overloaded as non-static class members
 - Short-circuit evaluation doesn't work with overloaded operators
 
[edit] Operator Calls
Overloaded operators can be called using the usual infix notation
a+bor a function-like notation
operator+(a,b)
[edit] Example
#include <iostream> using namespace std; class Fraction{ private: int numerator, denominator; public: Fraction(int n, int d): numerator(n), denominator(d) {} // Note that the keyword operator combined with an actual // operator is used as the function name friend ostream& operator<<(ostream&, Fraction&); }; ostream& operator<<(ostream& out, Fraction& f){ out << f.numerator << '/' << f.denominator; return out; } int main(){ Fraction f1(3, 8); Fraction f2(1, 2); cout << f1 << endl; cout << 3 << ' ' << f2 << endl; return 0; }
Output:
3/8 3 1/2
[edit] See Also
| Common operators | ||||||
|---|---|---|---|---|---|---|
| assignment |   increment decrement  | 
arithmetic | logical | comparison |   member access  | 
other | 
| 
 a = b  | 
 ++a  | 
 +a  | 
 !a  | 
 a == b  | 
 a[b]  | 
 a(...)  | 
| Special operators | ||||||
| 
 static_cast converts one type to another compatible type   | ||||||