#include <iostream>#include<stdio.h>#include<stdlib.h>using namespacestd;classoperat{floatx; floaty; Public: Operat (float_x =0,float_y =0) {x=_x; Y=_y; } operat (Operat&That ) {x=That.x; Y=That.y; } /*Operat operator + (operat& that)//member function + overload {Operat T; T.x = x + that.x; T.y = y + that.y; return t; } operat& operator + + (void)//member function pre + + Reload {x + +; y++; return *this; } Operat operator + + (int)//member function after + + overload {Operat T (*this); t.x++; t.y++; return t; }*/Operat&operator[] (inti)//member function [] overload {return*( This+i); } Operat&operator(void)//member function--overload {return* This; }
void Show ()
{
printf ("x=%f,y=%f\n", X, y);
}
Note: The normal function in the class and friend declaration into a class of friends can use the class member variables, otherwise the member variables are generally encapsulated in the class. The outside function is not available.
friend Operatoperator+ (operat& a,operat&b); Declare the friend function so that the external function can access the member variables of the class friend Operat&operator+ + (operat&a); Friend Operatoperator+ + (operat& A,int); Friend Ostream&operator<< (ostream& os,operat&p); Friend IStream&operator>> (istream& is,operat&p); ~Operat () {}};void*operator New(unsignedintsize)//overload of global function new {return malloc(size);} Operatoperator+ (operat& a,operat&b)//global function + overload {Operat T (a.x+b.x,a.y+b.y); returnT;} Operat&operator+ + (operat&a)//the overload of the global function before + + {a.x++; A.Y++; returnA;} Operatoperator+ + (operat& A,int)//global function after + + overload {Operat T=A; A.x++; A.Y++; returnT;} Ostream&operator<< (ostream& os,operat&p)//overload of global function << {returnOS <<"x="<< p.x <<" "<<"y="<< p.y <<" ";} IStream&operator>> (istream& is,operat&p)//overload of global function >> {return is>> p.x >>p.y;}intMain () {Operat A (1,2); Operat B (3,4); (A++). Show (); A.show (); CIN>>A; cout<< a << b <<Endl;}
Overloading of special operators in C + +