1. Output operator Overloading:
1#include <iostream>2#include"CString"3 4 using namespacestd;5 6 classComplex7 {8 Public:9Complex (intR=0,intI=0): _r (R), _i (i) {}Ten voidprint (); OneFriend ostream&operator<< (ostream& out,Constcomplex&_c); A Private: - int_r; - int_i; the }; - -ostream&operator<< (ostream& out,Constcomplex&_c) { - out<<"_r="<<_c._r<<"_i="<<_c._i<<Endl; + return out; - } + //cout<<c<<2 data into cout buffer ostream printf istream:cin A at //The return value type is not const-decorated and is typically used by friends - - //return value Why use the &:ostream class only and have only one object. - - //Why the return value cannot be const-decorated: COUT<<C1<<C2 - //if the return value is const-decorated, you cannot continue writing to the cout for output data. in //eg:cout<<c; // Right - //cout<<c<<endl; //Error to + //the second parameter,:const&, can receive either a const object or a non-const object. - //cannot exist as a member function because the first operand can only be a ostream type unique object cout and cannot be a custom type object. the voidComplex::p rint () * { $ if(_i==0) {Panax Notoginsengcout<<_r<<Endl; - } the Else if(_i<0){ +cout<<_r<<_i<<"I"<<Endl; A } the Else +cout<<_r<<"+"<<_i<<"I"<<Endl; - } $ intMainintargcConst Char*argv[]) { $cout<<"c1="; -Complex C1 (3,2); - c1.print (); thecout<<C1; - return 0;Wuyi}
2. Subscript operator Overloading:
1#include <iostream>2#include"CString"3 #defineSize 54 using namespacestd;5 6 classVector7 {8 Public:9 Const int&operator[](intIndexConst//Const Version: values that focus on reading elementsTen { One returnRep[index]; A } - int&operator[](intIndex//Non-const version: Focus on writing, modifying the value of an element - { the returnRep[index]; - } - Private: - intRep[size];//return value type: The element type in the container. + }; - +ostream&operator<< (ostream& out,Constvector&a) A { at for(intI=0; i<size; i++) { - out<<a[i]<<" ";//using the const version of the compiler calls the subscript overloaded function. - } - return out; - } - in - intMainintargcConst Char*argv[]) { to Vector x; +cout<<"Enter"<<size<<"integers.\n"; - for(intI=0; i<size; i++) { theCin>>X[i]; * } $ ConstVector y=x;Panax Notoginsengcout<<"x:"<<x<<Endl; -cout<<"y:"<<y<<Endl; thex[0]= -; +cout<<"x:"<<x<<Endl; Acout<<"y:"<<y<<Endl; the return 0; +}
C + + Fifth day Note February 22, 2016 (Monday) p.m.