Operator overloading in the C + + language is implemented by functions, so it is essentially a function overload, and when the original operator of the C + + language is overloaded, its original semantics do not disappear, it is equivalent to defining a new operator for a particular class.
<1> overloading operators with member functions
Example 1:
#include <iostream>using namespacestd;classrmb{ Public: RMB (unsignedintd,unsignedintc); RMBoperator+ (rmb&); RMB&operator++(); voiddisplay () {cout<< (yuan+jf/100.0) <<Endl; }protected: UnsignedintYuan; unsignedintThe JF;}; RMB::RMB (unsignedintd,unsignedintc) {Yuan=D; JF=C; while(jf>= -) {Yuan++; JF-= -; }}RMB RMB::operator+ (rmb&s) {unsignedintc=jf+S.JF; unsignedintd=yuan+S.yuan; RMB result (D,C); returnresult;} RMB& RMB::operator++() {JF++; if(jf>= -) {JF-= -; Yuan++; } return* This;}intMain () {$ D1 (1, -); $ D2 (2, -); $ d3 (0,0); D3=d1+D2; ++D3; D3.display (); return 0;}
Results: 4.11
Example 2:
#include <iostream>#include<string>using namespacestd;classstring{Charname[ the]; Public: String (Char*str) {strcpy (NAME,STR); } String () {}~string () {} stringoperator+(Conststring&); voiddisplay () {cout<<"The string is:"<<name<<Endl; }};Static Char*str; String string::operator+(Conststring&a) {strcpy (str,name); strcat (Str,a.name); returnString (str);//equivalent to return str; automatic type conversion}intMain () {str=New Char[ the]; String Demo1 ("Visual C + +"); String Demo2 ("6.0"); Demo1.display (); Demo2.display (); String Demo3=demo1+Demo2; Demo3.display (); String Demo4=demo3+"programming."; Demo4.display (); Deletestr; return 0;}
Results:
Example 3:
#include <iostream>#include<string>using namespacestd;classstring{Charname[ the]; Public: String (Char*str) {cout<<"constructor,char*--->string\n"; strcpy (NAME,STR); } string (String&s) {cout<<"Copy constructor\n"; strcpy (Name,s.name); } String () {cout<<"default constructor\n"; } ~String () {}void operator=(Conststring&s) {strcpy (name,s.name); cout<<"operator ="<<Endl; } Stringoperator+(Conststring&); voiddisplay () {cout<<"The string is:"<<name<<Endl; }};Static Char*str; String string::operator+(Conststring&a) {String s; cout<<"operator +\n"; strcpy (S.name,name); strcat (s.name,a.name);//return String (str);//equivalent to return str; automatic type conversion returns;}intMain () {str=New Char[ the]; String Demo1 ("Visual C + +"); String Demo2 ("6.0"); Demo1.display (); Demo2.display (); String Demo3; Demo3=demo1+Demo2; cout<<"---------------\ n"; Demo3.display (); String Demo4; Demo4=demo3+"programming."; Demo4.display (); Deletestr; cout<<"---------------\ n"; String Demo5=Demo4; Demo5.display (); return 0;}
Results:
PS: Pay attention to the application of copy-constructor!23333
<2> friend function overloading operator
Operator overloading in C + +