cpp/language/operators

From Cppreference

Jump to: navigation, search

Contents

[edit] Usage

Operator overloading


[edit] Syntax

[friend] <type> operator<op>([<type><variable>[, <type><variable>]]);
  1. <type> is/are the type(s) of the variables.
  2. <op> is the particular operator (e.g. +, +=, <<, >>, &&, ||, %, etc.).
  3. <variable> is/are the name(s) of the variable(s) used.
  4. Bold text must be typed as is
  5. Angle brackets denote a placeholder for a required value.
  6. Square brackets denote a placeholder for an optional value.
  7. Angle brackets nested inside square brackets indicate that it is required if anything inside the square brackets is used.
  8. 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;
 }