运算符重载的方法
运算符重载的方法是定义一个重载运算符的函数,使指定的运算符不仅能实现原有的功能,而且能实现在函数中指定的新的功能。运算符重载实质上是函数的重载。
函数重载的一般格式:
函数类型 operator 运算符名称(形参表){
对运算符的重载处理
}
使用例:(将 + 用于complex类的加法运算)
complex operator + (complex& c1,complex& c2);
重载运算符的规则
- C++不允许用户之间定义新的运算符,只能对已有的C++运算符进行重载。
- C++中的“ . ”,“ * ”,“ :: ”,“ sizeof ”,“ ?: ”运算符不能重载
- 重载不能改变运算符运算对象(即操作数)的个数
- 重载不能改变运算符的优先级别
- 重载不能改变运算符的结合性
- 重载运算符的函数不能有默认的参数
- 重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个是类对象(或类对象的引用)
- 用于类对象的运算符一般必须重载,但有两个例外,运算符“=”和“&”不必用户重载
- 从理论上说,可以将一个运算符重载为执行任意的操作,但根据实际情况的不同,应当使重载运算符的功能能类似于该运算符作用于标准类型数据时所实现的功能
重载双目运算符
例:
#include<iostream>
#include<string.h>
using namespace std;
class String{
public:
String(){
}
String(char *str);
friend bool operator >(String& st1,String& st2);
friend bool operator >(String& st1,String& st2);
friend bool operator ==(String& st1,String& st2);
void display();
private:
char * p;
};
String ::String(char *str){
p=str;
}
void String ::display(){
cout<<p;
}
bool operator >(String &st1,String &st2){
if(strcmp(st1.p,st2.p) >0){
return true;
}
else
return false;
}
bool operator <(String &st1,String &st2){
if(strcmp(st1.p,st2.p) <0){
return true;
}
else
return false;
}
bool operator ==(String &st1,String &st2){
if(strcmp(st1.p,st2.p) ==0){
return true;
}
else
return false;
}
void compare(String &st1,String &st2){
if(operator > (st1,st2)==1){
st1.display();cout<<">";st2.display();
}else
if(operator < (st1,st2)==1){
st1.display();cout<<"<";st2.display();
}else
if(operator == (st1,st2)==1){
st1.display();cout<<"=";st2.display();
}
cout<<endl;
}
int main(){
String st1("Hello"),st2("Book"),st3("Computer"),st4("Hello");
compare(st1,st2);
compare(st2,st3);
compare(st1,st4);
return 0;
}
重载单目运算符
例:
#include<iostream>
using namespace std;
class Time{
public:
Time(){
minute=0;sec=0;
}
Time(int m,int s):minute(m),sec(s){
}
Time operator ++();
Time operator ++(int);
void display(){
cout<<minute<<":"<<sec<<endl;
}
private:
int minute;
int sec;
};
Time Time::operator ++(){
if(++sec>=60){
sec-=60;
++minute;
}
return *this;
}
Time Time::operator ++(int){
Time temp(*this);
sec++;
if(sec>=60){
sec-=60;
++minute;
}
return temp;
}
int main(){
Time time1(34,59),time2;
cout<<"time1:";
time1.display();
++time1;
cout<<"++time1:";
time1.display();
time2=time1++;
cout<<"time1++:";
time1.display();
cout<<"time2:";
time2.display();
return 0;
}
重载流插入运算符和流提取运算符
重载流插入运算符"<<"
函数形式:
istream & operator >> (istream &,自定义类 &);
重载流提取运算符">>"
函数形式:
ostream & operator << (ostream &,自定义类 &);