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>=){
yuan++;
jf-=;
}
}
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>=){
jf-=;
yuan++;
}
return *this;
}
int main(){
RMB d1(,);
RMB d2(,);
RMB d3(,);
d3=d1+d2;
++d3;
d3.display();
return ;
}
结果:4.11
例2:
#include <iostream>
#include <string>
using namespace std;
class String
{
char name[];
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[];
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 ;
}
结果:
例3:
#include <iostream>
#include <string>
using namespace std;
class String
{
char name[];
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=(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 +\n";
strcpy(s.name,name);
strcat(s.name,a.name);
// return String(str);//等价于return str;进行自动类型转换
return s;
}
int main(){
str=new char[];
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();
delete str;
cout<<"---------------\n";
String demo5=demo4;
demo5.display();
return ;
}
结果:
ps:注意拷贝构造函数的应用!23333
<2>友元函数重载运算符