cpp/language/operators
From Cppreference
Contents |
[edit] Usage
Operator overloading
[edit] Syntax
[friend] <type> operator<op>([<type><variable>[, <type><variable>]]);
- <type> is/are the type(s) of the variables.
- <op> is the particular operator (e.g. +, +=, <<, >>, &&, ||, %, etc.).
- <variable> is/are the name(s) of the variable(s) used.
- Bold text must be typed as is
- Angle brackets denote a placeholder for a required value.
- Square brackets denote a placeholder for an optional value.
- Angle brackets nested inside square brackets indicate that it is required if anything inside the square brackets is used.
- Operators must accept the correct number of arguments to be properly overloaded.
[edit] Restrictions
You cannot create new operators such as ** or &|.
[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; //The output should be "3/8" cout << 3 << ' ' << f2 << endl; //The ouput should be "3 1/2" return 0; }