c++语言中运算符重载都是通过函数来实现的,所以其实质为函数重载,当c++语言原有的一个运算符被重载之后,它原来所具有的语义并没有消失,只相当于针对一个特定的类定义了一个新的运算符。
<1>用成员函数重载运算符
例1:
#include <iostream> using namespace std; class RMB{ public: RMB(unsigned int d,unsigned int c); RMB operator+(RMB&); RMB& operator++(); void display(){ cout<<(yuan+jf/100.0)<<endl; } protected: unsigned int yuan; unsigned int jf; }; RMB::RMB(unsigned int d,unsigned int c){ yuan=d; jf=c; while(jf>=100){ yuan++; jf-=100; } } RMB RMB::operator +(RMB& s){ unsigned int c=jf+s.jf; unsigned int d=yuan+s.yuan; RMB result(d,c); return result; } RMB& RMB::operator++(){ jf++; if(jf>=100){ jf-=100; yuan++; } return *this; } int main(){ RMB d1(1,60); RMB d2(2,50); RMB d3(0,0); d3=d1+d2; ++d3; d3.display(); return 0; }
结果:4.11
例2:
#include <iostream> #include <string> using namespace std; class String { char name[256]; public: String(char* str){ strcpy(name,str); } String(){ } ~String(){ } String operator+(const String&); void display(){ cout<<"The string is:"<<name<<endl; } }; static char* str; String String::operator+(const String& a){ strcpy(str,name); strcat(str,a.name); return String(str);//等价于return str;进行自动类型转换 } int main(){ str=new char[256]; String demo1("Visual C++"); String demo2("6.0"); demo1.display(); demo2.display(); String demo3=demo1+demo2; demo3.display(); String demo4=demo3+"Programming ."; demo4.display(); delete str; return 0; }
结果:
例3:
#include <iostream> #include <string> using namespace std; class String { char name[256]; public: String(char* str){ cout<<"constructor,char*--->String "; strcpy(name,str); } String(String &s){ cout<<"copy constructor "; strcpy(name,s.name); } String(){ cout<<"default constructor "; } ~String(){ } void operator=(const String&s){ strcpy(name,s.name); cout<<"operator ="<<endl; } String operator+(const String&); void display(){ cout<<"The string is:"<<name<<endl; } }; static char* str; String String::operator+(const String& a){ String s; cout<<"operator + "; strcpy(s.name,name); strcat(s.name,a.name); // return String(str);//等价于return str;进行自动类型转换 return s; } int main(){ str=new char[256]; String demo1("Visual C++"); String demo2("6.0"); demo1.display(); demo2.display(); String demo3; demo3=demo1+demo2; cout<<"--------------- "; demo3.display(); String demo4; demo4=demo3+"Programming ."; demo4.display(); delete str; cout<<"--------------- "; String demo5=demo4; demo5.display(); return 0; }
结果:
ps:注意拷贝构造函数的应用!23333
<2>友元函数重载运算符