重载

函数重载


一、什么是函数重载?

函数重载overload是指不同的函数采用相同的函数名,彼此间通过形参列表加以区分。

举例:

函数名都为distance,但形参列表的个数不同;

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <cmath>  
  3. using namesapce std;  
  4. double distance(float,float);  
  5. double distance(float,float,float,float);  
  6. int main()  
  7. {  
  8.     float point1X,point1Y,point2X,point2Y;  
  9.     point1X=5.0;  
  10.     point1Y=5.0;  
  11.     point2X=7.0;  
  12.     point2Y=7.0;  
  13.     cout<<"The distance to the origin is:\n";  
  14.     cout<<"Point 1 ("<<point1X<<","<<point1Y<<"): "<<distance(point1X,point1Y)<<endl;  
  15.     cout<<"Point 2 ("<<point2X<<","<<point2Y<<"): "<<distance(point2X,point2Y)<<endl;  
  16.     cout<<"The distance between two points ("<<point1X<<","<<point1Y<<") and ("  
  17.         <<point2X<<","<<point2Y<<") is "<<distance(point1X,point1Y,point2X,point2Y)<<endl;  
  18.     return 0;  
  19. }  
  20. double distance(float pX,float pY)  
  21. {  
  22.     return sqrt(pX*pX+pY*pY);  
  23. }  
  24. double distance(float p1X,float p1Y,float p2X,float p2Y)  
  25. {  
  26.     return sqrt((p2X-p1X)*(p2X-p1X)+(p2Y-p1Y)*(p2Y-p1Y));  
  27. }  

函数名都为equal,但形参列表的数据类型不同;

[cpp]  view plain  copy
  1. #include <iostream>  
  2. using namesapce std;  
  3. bool equal(int,int);  
  4. bool equal(float,float);  
  5. bool equal(char*,char*);  
  6.   
  7. int main()  
  8. {  
  9.     int i1,i2;  
  10.     float f1,f2;  
  11.     char *c1,*c2;  
  12.     i1=3;i2=6;  
  13.     f1=3.33333;f2=3.33332;  
  14.     c1=new char[20];c2=new char[20];  
  15.     strcpy(c1,"Hello");  
  16.     strcpy(c2,"hello");  
  17.     switch(equal(i1,i2))  
  18.     {  
  19.         case true:  
  20.             cout<<i1<<"=="<<i2<<endl;break;  
  21.         case false:  
  22.             cout<<i1<<"!="<<i2<<endl;break;  
  23.     }  
  24.     switch(equal(f1,f2))  
  25.     {  
  26.         case true:  
  27.             cout<<f1<<"=="<<f2<<endl;break;  
  28.         case false:  
  29.             cout<<f1<<"!="<<f2<<endl;break;  
  30.     }  
  31.     switch(equal(c1,c2))  
  32.     {  
  33.         case true:  
  34.             cout<<c1<<"=="<<c2<<endl;break;  
  35.         case false:  
  36.             cout<<c1<<"!="<<c2<<endl;break;  
  37.     }  
  38.     delete[] c1;delete[] c2;  
  39.     return 0;  
  40. }  
  41. bool equal(int a,int b)  
  42. {  
  43.     return a==b?true:false;  
  44. }  
  45. bool equal(float a,float b)  
  46. {  
  47.     if(fabs(a-b)<1e-6)  
  48.         return true;  
  49.     else   
  50.         return false;  
  51. }  
  52. bool equal(char* a,char* b)  
  53. {  
  54.     if(strcmp(a,b)==0)  
  55.         return true;  
  56.     else  
  57.         return false;  
  58. }  

类的构造函数是函数重载使用最普遍的地方;

[cpp]  view plain  copy
  1. <pre name="code" class="cpp">#include <iostream>  
  2. #include <string>  
  3. using namesapce std;  
  4. class ScoreRec{  
  5. public:  
  6.     ScoreRec()  
  7.     {  
  8.         name="";  
  9.         ID="";  
  10.         score=' ';  
  11.     }  
  12.     ScoreRec(string newName,string newID,char newScore)  
  13.     {  
  14.         name=newName;  
  15.         ID=newID;  
  16.         Score=newScore;  
  17.     }  
  18.     void getRecord(string& nameGet,string& IDGet,char& scoreGet)  
  19.     {  
  20.         nameGet=name;  
  21.         IDGet=ID;  
  22.         scoreGet=score;  
  23.     }  
  24. private:  
  25.     string name;  
  26.     string ID;  
  27.     char score;  
  28. };  
  29. int main()  
  30. {  
  31.     ScoreRec A;  
  32.     ScoreRec B("Henry","123456","B");  
  33.     string name,id;  
  34.     char score;  
  35.     A.getRecord(name,id,score);  
  36.     cout<<name<<endl<<id<<endl<<score<<endl;  
  37.     B.getRecord(name,id,score);  
  38.     cout<<name<<endl<<id<<endl<<score<<endl;  
  39.     return 0;  
  40. }  


二、为什么使用函数重载?

在不同情形下,虽然处理数据的个数、数据类型可能不同,但用相同的函数名表达本质上相同的操作更符合人们的习惯,故函数重载给编程提供便利。


三、使用函数重载时需要注意的问题

1 .若函数名、函数形参个数及对应的数据类型都相同,只是函数的返回类型不同,则不是有效的函数重载;编译时出现“函数定义重复”错误;


2 .若函数返回类型、函数名、形参个数及对应数据类型相同,只有参数传递方式不同,则不是有效的函数重载;


3 .调用重载函数时的二义性问题

3.1 隐式类型转换引起的二义性问题

在赋值、参数传递等情形下,当数据类型不匹配时,编译器会自动进行数据类型转换,即隐式类型转换;

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <cmath>  
  3. using namesapce std;  
  4. bool equal(int,int);  
  5. bool equal(double,double);  
  6. int main()  
  7. {  
  8.     int i;  
  9.     double d;  
  10.     i=3;  
  11.     d=3.0;  
  12.     switch(equal(i,d))  
  13.     {  
  14.         case true:  
  15.             cout<<i<<"=="<<d<<endl;  
  16.             break;  
  17.         case false:  
  18.             cout<<i<<"!="<<d<<endl;  
  19.             break;  
  20.     }  
  21.     return 0;  
  22. }  
  23. bool equal(int a,int b)  
  24. {  
  25.     return a==b?true:false;  
  26. }  
  27. bool equal(double a,double b)  
  28. {  
  29.     if(fabs(a-b)<1e-6)  
  30.         return true;  
  31.     else   
  32.         return false;  
  33. }  

编译上述程序,出现以下错误:

error C2666: 'equal' : 2 overloads have similar conversions.

原因是可将equal(i,d)调用中的i转换成d型,也可将d转换成i型,编译器无法确定如何转换,因为两种转换都有相应的函数对应;

3.2 使用默认参数时的二义性

使用默认参数的函数本身就是将几个重载函数合而为一;

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <cmath>  
  3. using namesapce std;  
  4. double distance(float,float);  
  5. double distance(float,float,float x=0,float y=0);  
  6. int main()  
  7. {  
  8.     float point1X,point1Y,point2X,point2Y;  
  9.     point1X=5.0;  
  10.     point1Y=5.0;  
  11.     point2X=7.0;  
  12.     point2Y=7.0;  
  13.     cout<<"The distance to the origin is:\n";  
  14.     cout<<"Point 1 ("<<point1X<<","<<point1Y<<"): "<<distance(point1X,point1Y)<<endl;  
  15.     return 0;  
  16. }  
  17. double distance(float pX,float pY)  
  18. {  
  19.     return sqrt(pX*pX+pY*pY);  
  20. }  
  21. double distance(float p1X,float p1Y,float p2X,float p2Y)  
  22. {  
  23.     return sqrt((p2X-p1X)*(p2X-p1X)+(p2Y-p1Y)*(p2Y-p1Y));  
  24. }  

编译上述程序,出现以下错误:

error C2668: 'distance' : ambiguous call to overloaded function.

原因是double distance(float p1X,float p1Y,float p2X=0,float p2Y=0)使用默认参数,它实际上是多个函数的集合体:

若调用该函数时,给出4个实际参数,相当于调用double distance(float p1X,float p1Y,float p2X,float p2Y)函数;

若调用该函数时,给出3个实际参数,相当于调用double distance(float p1X,float p1Y,float p2X)函数,同时将函数体中的p2Y设为0;

若调用该函数时,给出2个实际参数,相当于调用double distance(float p1X,float p1Y)函数,同时将函数体中的p2X和p2Y设为0,实际上等价于求到原点的距离;

在main函数中调用distance(point1X,point1Y)函数时,编译器无法确定调用的是哪个distance函数;

注意:

在指定默认参数时,必须从参数表的最右边开始并连续指定默认参数。


复制构造函数


一、复制构造函数对的语法形式

复制构造函数的形参类型是类类型本身,且使用引用方式进行参数的传递。复制构造函数的原型形式如:X(const X&)

其中,X是类名,形参通常指定为const;

举例:

[cpp]  view plain  copy
  1. class Computer{  
  2. public:  
  3.     Computer(const Computer& anotherComputer);  
  4. };  


二、复制构造函数的使用场合

若程序员没有为类定义复制构造函数,编译器会自动生成一个复制构造函数。

1. 用已有的对象对新对象进行初始化

举例1:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namesapce std;  
  4. class ScoreRec{  
  5. public:  
  6.     ScoreRec()  
  7.     {  
  8.         name="";  
  9.         ID="";  
  10.         score=' ';  
  11.         cout<<"Default constructor.\n";  
  12.     }  
  13.     ScoreRec(string newName,string newID,char newScore)  
  14.     {  
  15.         name=newName;  
  16.         ID=newID;  
  17.         Score=newScore;  
  18.         cout<<"Constructor with parameters.\n";  
  19.     }  
  20.     ScoreRec(const ScoreRec& anotherScoreRec)  
  21.     {  
  22.         name=anotherScoreRec.name;  
  23.         ID=anotherScoreRec.ID;  
  24.         score=anotherScoreRec.score;  
  25.         cout<<"Copy constructor.\n";  
  26.     }  
  27.     void getRecord(string& nameGet,string& IDGet,char& scoreGet)  
  28.     {  
  29.         nameGet=name;  
  30.         IDGet=ID;  
  31.         scoreGet=score;  
  32.     }  
  33. private:  
  34.     string name;  
  35.     string ID;  
  36.     char score;  
  37. };  
  38. int main()  
  39. {  
  40.     ScoreRec A;  
  41.     ScoreRec B("Henry","123456","B");  
  42.     ScoreRec C(B);  
  43.     string name,id;  
  44.     char score;  
  45.     A.getRecord(name,id,score);  
  46.     cout<<name<<endl<<id<<endl<<score<<endl;  
  47.     B.getRecord(name,id,score);  
  48.     cout<<name<<endl<<id<<endl<<score<<endl;  
  49.     C.getRecord(name,id,score);  
  50.     cout<<name<<endl<<id<<endl<<score<<endl;  
  51.     return 0;  
  52. }  

上述程序的运行结果:

Default constructor.

Constructor with parameters.

Copy constructor.




Henry

123456

B

Henry

123456

B

分析:

ScoreRec A;语句生成一个ScoreRec对象,每个对象的初始化由默认构造函数完成,则有Default constructor.输出;

ScoreRec B("Henry","123456",'B');语句调用带参数的构造函数,则有Constructor with parameters.输出;该语句用参数对对象B的数据成员进行初始化;

ScoreRec C(B);语句调用复制构造函数,用已有的对象B初始化新的对象C,则有Copy constructor.输出;用已有的对象初始化新对象时,新对象的数据成员的值和已有对象的数据成员的值完全相等;

注意:

编译器自动生成的复制构造函数的工作是将已有对象的内存空间中的数据按位复制一份到新对象的内存空间,称为浅复制。

浅复制采用按位复制方法,当类的数据成员中有指针,会引发一些意想不到的问题。

举例2:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namesapce std;  
  4. class ScoreRec{  
  5. public:  
  6.     ScoreRec()  
  7.     {  
  8.         name=NULL;  
  9.         ID=NULL;  
  10.         score=' ';  
  11.         cout<<"Default constructor.\n";  
  12.     }  
  13.     ~ScoreRec()  
  14.     {  
  15.         if(name!=NULL)  
  16.             delete[] name;  
  17.         if(ID!=NULL)  
  18.             delete[] ID;  
  19.         cout<<"Deconstructor.\n";  
  20.     }  
  21.     ScoreRec(char* newName,char* newID,char newScore)  
  22.     {  
  23.         name=new char[strlen(newName)+1];  
  24.         strcpy(name,newName);  
  25.         ID=new char[strlen(newID)+1];  
  26.         strcpy(ID,newID);  
  27.         Score=newScore;  
  28.         cout<<"Constructor with parameters.\n";  
  29.     }  
  30.     ScoreRec(const ScoreRec& anotherScoreRec)  
  31.     {  
  32.         name=new char[strlen(anotherScoreRec.name)+1];  
  33.         ID=new char[strlen(anotherScoreRec.ID)+1];  
  34.         strcpy(name,anotherScoreRec.name);  
  35.         strcpy(ID,anotherScoreRec.ID);  
  36.         score=anotherScoreRec.score;  
  37.         cout<<"Copy constructor.\n";  
  38.     }  
  39.     void getRecord(string& nameGet,string& IDGet,char& scoreGet)  
  40.     {  
  41.         strcpy(nameGet,name);  
  42.         strcpy(IDGet,Id);  
  43.         scoreGet=score;  
  44.     }  
  45. private:  
  46.     char* name;  
  47.     char* ID;  
  48.     char score;  
  49. };  
  50. int main()  
  51. {  
  52.     ScoreRec B("Henry","123456","B");  
  53.     ScoreRec C(B);  
  54.     char name[50],id[50];  
  55.     char score;  
  56.     B.getRecord(name,id,score);  
  57.     cout<<name<<endl<<id<<endl<<score<<endl;  
  58.     C.getRecord(name,id,score);  
  59.     cout<<name<<endl<<id<<endl<<score<<endl;  
  60.     return 0;  
  61. }  

上述程序的运行结果:

Constructor with parameters.

Copy constructor.

Henry

123456

B

Henry

123456

B

Deconstructor.

Deconstructor.

分析:

由于ScoreRec类的数据成员使用指针类型,故特别留意内存空间的申请与释放!

在上述程序中,内存空间的申请放在构造函数中,空间的释放放在析构函数中;构造函数在创建类对象时调用,析构函数在类对象的生命周期结束时调用;

如下图为复制构造函数执行后两个ScoreRec类对象的内存情况,B和C中name的值不同,ID的值也不同。由于name和ID是指针数据类型,可理解为B和C中,name指向不同的内存空间,ID指向不同的内存空间;但内存空间中存储的是相同的内容,称为深复制,将一个对象中指针成员所指的内存空间的内容复制到另一个对象对应指针成员所指的内存空间中。


若没有定义复制构造函数,编译器会自动生成一个复制构造函数。编译器自动生成的复制构造函数通过浅复制将已有对象中指针成员所指向的内存空间中的数据按位复制一份到新对象的对应指针成员所指向的内存空间。如下图为浅复制构造函数执行后两个ScoreRec类对象的内存情况。由于name和ID是指针类型数据,可理解为按位复制后,B和C中name指向相同的内存空间,ID也指向相同的内存空间。


当对象的生命期结束时,系统会自动调用解析函数。同一内存的重复释放会导致运行时错误。这一点在类的数据成员中包含有指针时,需要特别注意!因此,需要程序员自己定义复制构造函数,通过深复制解决多个指针指向同一内存的问题。深复制时,B和C的name值是分别通过new操作赋值的,指向不同内存空间,不会出现同一内存空间的重复释放。


2 .调用以值形参传递类对象的函数

举例:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namesapce std;  
  4. class ScoreRec{  
  5. public:  
  6.     ScoreRec()  
  7.     {  
  8.         name=NULL;  
  9.         ID=NULL;  
  10.         score=' ';  
  11.         cout<<"Default constructor.\n";  
  12.     }  
  13.     ~ScoreRec()  
  14.     {  
  15.         if(name!=NULL)  
  16.             delete[] name;  
  17.         if(ID!=NULL)  
  18.             delete[] ID;  
  19.         cout<<"Deconstructor.\n";  
  20.     }  
  21.     ScoreRec(char* newName,char* newID,char newScore)  
  22.     {  
  23.         name=new char[strlen(newName)+1];  
  24.         strcpy(name,newName);  
  25.         ID=new char[strlen(newID)+1];  
  26.         strcpy(ID,newID);  
  27.         Score=newScore;  
  28.         cout<<"Constructor with parameters.\n";  
  29.     }  
  30.     ScoreRec(const ScoreRec& anotherScoreRec)  
  31.     {  
  32.         name=new char[strlen(anotherScoreRec.name)+1];  
  33.         ID=new char[strlen(anotherScoreRec.ID)+1];  
  34.         strcpy(name,anotherScoreRec.name);  
  35.         strcpy(ID,anotherScoreRec.ID);  
  36.         score=anotherScoreRec.score;  
  37.         cout<<"Copy constructor.\n";  
  38.     }  
  39.     void getRecord(string& nameGet,string& IDGet,char& scoreGet)  
  40.     {  
  41.         strcpy(nameGet,name);  
  42.         strcpy(IDGet,Id);  
  43.         scoreGet=score;  
  44.     }  
  45. private:  
  46.     char* name;  
  47.     char* ID;  
  48.     char score;  
  49. };  
  50. void writeScoreRec(ScoreRec rec)  
  51. {  
  52.     char name[50],id[50];  
  53.     char score;  
  54.     rec.getRecord(name,id,score);  
  55.     cout<<name<<endl<<id<<endl<<score<<endl;  
  56.     return;  
  57. }  
  58. int main()  
  59. {  
  60.     ScoreRec B("Henry","123456","B");  
  61.     ScoreRec C(B);  
  62.     writeScoreRec(B);  
  63.     writeScoreRec(C);  
  64.     return 0;  
  65. }  

上述程序的运行结果:

Constructor with parameters.

Copy constructor.

Copy constructor.

Henry

123456

B

Deconstructor.

Copy constructor.

Henry

123456

B

Deconstructor.

Deconstructor.

Deconstructor.

分析:

writeScoreRec的形参rec相当于局部对象,将实参B传递给形参rec,相当于用已有对象初始化新对象,需要调用复制构造函数,因此输出Copy constructor.;

当函数writeScoreRec返回时,局部对象rec的生命周期结束,需要调用析构函数,因此输出Deconstructor.;

向值形参传递实参时,需生成一个实参的副本。当函数以值传递的方式进行类对象的传递时,会导致复制构造函数的调用,其语义相对复杂,因此在以类对象作为参数时,应使用引用形参的方式定义类对象的传递。


3 .调用返回值为类对象的函数

增加函数setScoreRec,用以生成一个ScoreRec对象,根据参数设置该对象的属性数据,并返回该对象。

举例:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namesapce std;  
  4. class ScoreRec{  
  5. public:  
  6.     ScoreRec()  
  7.     {  
  8.         name=NULL;  
  9.         ID=NULL;  
  10.         score=' ';  
  11.         cout<<"Default constructor.\n";  
  12.     }  
  13.     ~ScoreRec()  
  14.     {  
  15.         if(name!=NULL)  
  16.             delete[] name;  
  17.         if(ID!=NULL)  
  18.             delete[] ID;  
  19.         cout<<"Deconstructor.\n";  
  20.     }  
  21.     ScoreRec(char* newName,char* newID,char newScore)  
  22.     {  
  23.         name=new char[strlen(newName)+1];  
  24.         strcpy(name,newName);  
  25.         ID=new char[strlen(newID)+1];  
  26.         strcpy(ID,newID);  
  27.         Score=newScore;  
  28.         cout<<"Constructor with parameters.\n";  
  29.     }  
  30.     ScoreRec(const ScoreRec& anotherScoreRec)  
  31.     {  
  32.         name=new char[strlen(anotherScoreRec.name)+1];  
  33.         ID=new char[strlen(anotherScoreRec.ID)+1];  
  34.         strcpy(name,anotherScoreRec.name);  
  35.         strcpy(ID,anotherScoreRec.ID);  
  36.         score=anotherScoreRec.score;  
  37.         cout<<"Copy constructor.\n";  
  38.     }  
  39.     void getRecord(string& nameGet,string& IDGet,char& scoreGet)  
  40.     {  
  41.         strcpy(nameGet,name);  
  42.         strcpy(IDGet,Id);  
  43.         scoreGet=score;  
  44.     }  
  45.     void setName(char* newName)  
  46.     {  
  47.         if(name!=NULL)  
  48.             delete[] name;  
  49.         name=new char[strlen(newName)+1];  
  50.         strcpy(name,newName);  
  51.     }  
  52.     void setID(char* newID)  
  53.     {  
  54.         if(ID!=NULL)  
  55.             delete[] ID;  
  56.         ID=new char[strlen(newID)+1];  
  57.         strcpy(ID,newID);  
  58.     }  
  59.     void setScore(char newScore)  
  60.     {  
  61.         score=newScore;  
  62.     }  
  63. private:  
  64.     char* name;  
  65.     char* ID;  
  66.     char score;  
  67. };  
  68. ScoreRec setScoreRec(char* newName, char* newID, char newScore)  
  69. {  
  70.     ScoreRec tempRec;  
  71.     tempRec.setName(newName);  
  72.     tempRec.setID(newID);  
  73.     tempRec.setScore(newScore);  
  74.     return tempRec;  
  75. }  
  76. void writeScoreRec(ScoreRec rec)  
  77. {  
  78.     char name[50],id[50];  
  79.     char score;  
  80.     rec.getRecord(name,id,score);  
  81.     cout<<name<<endl<<id<<endl<<score<<endl;  
  82.     return;  
  83. }  
  84. int main()  
  85. {  
  86.     char stuName[50]="Henry";  
  87.     char stuID[50]="123456";  
  88.     char stuScore='B';  
  89.     writeScoreRec(setScoreRec(stuName,stuID,stuScore));  
  90.     return 0;  
  91. }  

上述程序的运行结果:

Default constructor.

Copy constructor.

Deconstructor.

Henry

123456

B

Deconstructor.

分析:

setScoreRec函数中有ScoreRec tempRec;语句,调用默认构造函数,输出Default constructor.

setScoreRec函数中将tempRec的各项数据进行设置,再return tempRec;语句。当以值方式返回类对象时,系统实际创建一个临时的全局类对象(假设为tempObj),作为待返回对象的副本,并调用复制构造函数初始化tempObj对象。return tempRec;语句会导致一个tempObj的创建即复制构造函数的调用;同时由于setScoreRec函数返回,tempRec生命期结束,需要调用析构函数。

最后一个Deconstructor.用于撤销tempObj。


操作符重载


操作符重载是指同一个操作符表示不同的实际操作;

一、C++操作符的函数特性

若将C++的操作符看作函数,操作数看作函数的参数,则一元操作符有一个参数,二元操作符有两个参数;

如加法操作符是二元操作符,a+b可写成函数的调用方式+ (a, b);

操作符具有函数的特性,也可像函数一样进行重载;操作符的重载可通过类的成员函数实现,也可通过友元函数实现;


二、操作符重载的规则

1. 不是所有的操作符都可重载

常见的不能重载的操作符包括:

::  .   .*  ?:      sizeof


2 .实现操作符重载的方法

可用成员函数对操作符进行重载,也可用友元函数对操作符进行重载;

操作符重载后对从操作符做出解释,但原有的基本语义,包括操作符的优先级、结核性和所需要的操作数个数均保持不变;

注意:=、[]、()、->等操作符只能使用类成员函数进行重载!


三、类成员函数操作符重载

1. 语法及实例

操作符是一种特殊的成员函数,其语法形式为:

[cpp]  view plain  copy
  1. <em>返回值类型 类名</em>:: operator <em>操作符 </em>(<em>形参列表</em>)  
  2. {  
  3.     <em>函数体代码</em>  
  4. }  

举例:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <ctime>  
  3. using namespace std;  
  4. class StopWatch{      // 秒表类  
  5. public:  
  6.     StopWatch();  
  7.     void setTime(int newMin, int newSec);  
  8.     StopWatch operator - (StopWatch&);  
  9.     void showTime();  
  10. private:  
  11.     int min;  
  12.     int sec;  
  13. };  
  14. StopWatch::StopWatch()  
  15. {  
  16.     min = 0;  
  17.     sec = 0;  
  18. }  
  19. void StopWatch::setTime(int newMin, int newSec)  
  20. {  
  21.     min = newMin;  
  22.     sec = newSec;  
  23. }  
  24. StopWatch StopWatch::operator - (StopWatch& anotherTime)  
  25. {  
  26.     StopWatch tempTime;  
  27.     int seconds;  
  28.     seconds = min * 60 + sec - (anotherTime.min * 60 + anotherTime.sec);  
  29.     if (seconds < 0)  
  30.     {  
  31.         seconds = -seconds;  
  32.     }  
  33.     tempTime.min = seconds / 60;  
  34.     tempTime.sec = seconds % 60;  
  35.     return tempTime;  
  36. }  
  37. void StopWatch::showTime()  
  38. {  
  39.     if (min>0)  
  40.         cout << min << " minutes " << sec << "seconds" << endl;  
  41.     else  
  42.         cout << sec << " seconds" << endl;  
  43. }  
  44.   
  45. int main()  
  46. {  
  47.     StopWatch startTime, endTime, usedTime;  
  48.     cout << "Press enter key to start.";  
  49.     cin.get();  
  50.     time_t curtime = time(0);  
  51.     tm tim = *localtime(&curtime);  
  52.     int min, sec;  
  53.     min = tim.tm_min;  
  54.     sec = tim.tm_sec;  
  55.     startTime.setTime(min, sec);  
  56.   
  57.     cout << "Press enter key to start.";  
  58.     cin.get();  
  59.     curtime = time(0);  
  60.     tim = *localtime(&curtime);  
  61.     min = tim.tm_min;  
  62.     sec = tim.tm_sec;  
  63.     endTime.setTime(min, sec);  
  64.   
  65.     usedTime = endTime - startTime;  
  66.     cout << "Used time: ";  
  67.     usedTime.showTime();  
  68.   
  69.     system("pause");  
  70.     return 0;  
  71. }  

运行结果:

Press enter key to start.<回车>

Press enter key to start.<回车>

Used time: 5 seconds

分析:

在上述StopWatch类中,我们重载了-操作符,实现了两个秒表时间之间的差操作;这里重载的是二元操作符;

重载操作符的成员函数的函数头为:StopWatch StopWatch::operator - (StopWatch& anotherTime)

其中包含以下信息:

a 函数名是operator -,表示重载操作符-

b StopWatch::表示重载该操作符的类是StopWatch类

c 该函数的返回类型是StopWatch类

d 该函数带一个参数,参数类型是StopWatch类,应以引用方式传递

在main函数中usedTime=endTime-startTime;解释为usedTime=endTime.operator - (startTime);

即调用endTime的operator -函数,参数是startTime,返回值赋值给usedTime;


2 .参数个数和操作数个数的关系

用成员函数实现操作符重载,函数参数个数个操作符所带操作数个数之间有以下规则:

2.1 一元操作符实现为不带参数的成员函数

2.2 二元操作符实现为带一个参数的成员函数

注意:假设我们把二元操作符的操作数分别称为左操作数和右操作数,用成员函数重载时,则函数的参数中只包含右操作数,左操作数是调用该函数的类对象,该类对象通过this指针隐含传递给操作符函数;


3 .典型的操作符重载:赋值操作符重载

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. class ScoreRec{  
  6. public:  
  7.     ScoreRec()  
  8.     {  
  9.         name = NULL;  
  10.         ID = NULL;  
  11.         score = ' ';  
  12.         cout << "Default constructor." << endl;  
  13.     }  
  14.     ScoreRec(char* newName, char* newID, char newScore)  
  15.     {  
  16.         name = new char[strlen(newName) + 1];  
  17.         strcpy(name, newName);  
  18.         ID = new char[strlen(newID) + 1];  
  19.         strcpy(ID, newID);  
  20.         score = newScore;  
  21.         cout << "Constructor with parameters." << endl;  
  22.     }  
  23.     ~ScoreRec()  
  24.     {  
  25.         if (name!=NULL)  
  26.             delete[] name;  
  27.         if(ID!=NULL)  
  28.             delete[] ID;  
  29.         cout << "Deconstructor." << endl;  
  30.     }  
  31.     ScoreRec(ScoreRec& anotherScoreRec)  
  32.     {  
  33.         name = new char[strlen(anotherScoreRec.name) + 1];  
  34.         strcpy(name, anotherScoreRec.name);  
  35.         ID = new char[strlen(anotherScoreRec.ID) + 1];  
  36.         strcpy(ID, anotherScoreRec.ID);  
  37.         score = anotherScoreRec.score;  
  38.         cout << "Copy constructor." << endl;  
  39.     }  
  40.     void getScoreRec(char* nameGet, char* IDGet, char& scoreGet)  
  41.     {  
  42.         strcpy(nameGet, name);  
  43.         strcpy(IDGet, ID);  
  44.         scoreGet = score;  
  45.     }  
  46.     void setName(char* newName)  
  47.     {  
  48.         if (name != NULL)  
  49.             delete[] name;  
  50.         name = new char[strlen(newName) + 1];  
  51.         strcpy(name, newName);  
  52.     }  
  53.     void setID(char* newID)  
  54.     {  
  55.         if (ID != NULL)  
  56.             delete[] ID;  
  57.         ID = new char[strlen(newID)+1];  
  58.         strcpy(ID, newID);  
  59.     }  
  60.     void setScore(char newScore)  
  61.     {  
  62.         score = newScore;  
  63.     }  
  64.     ScoreRec& operator = (ScoreRec& anotherScoreRec)  
  65.     {  
  66.         if (name != NULL)  
  67.             delete[] name;  
  68.         if (ID != NULL)  
  69.             delete[] ID;  
  70.         name = new char[strlen(anotherScoreRec.name)+1];  
  71.         strcpy(name, anotherScoreRec.name);  
  72.         ID = new char[strlen(anotherScoreRec.ID)+1];  
  73.         strcpy(ID, anotherScoreRec.ID);  
  74.         score = anotherScoreRec.score;  
  75.         return *this;  
  76.     }  
  77. private:  
  78.     char* name;  
  79.     char* ID;  
  80.     char score;  
  81. };  
  82. ScoreRec setScoreRec(char* newName, char* newID, char newScore)  
  83. {  
  84.     ScoreRec tempRec;  
  85.     tempRec.setName(newName);  
  86.     tempRec.setID(newID);  
  87.     tempRec.setScore(newScore);  
  88.     return tempRec;  
  89. }  
  90. void writeScoreRec(ScoreRec rec)  
  91. {  
  92.     char name[50], id[50];  
  93.     char score;  
  94.     rec.getScoreRec(name, id, score);  
  95.     cout << name << endl << id << endl << score << endl;  
  96.     return;  
  97. }  
  98. int main()  
  99. {  
  100.     char stuName[50] = "Henry";  
  101.     char stuID[50] = "123456";  
  102.     char stuScore = 'A';  
  103.   
  104.     ScoreRec tempRec;  
  105.     tempRec = setScoreRec(stuName, stuID, stuScore);  
  106.     writeScoreRec(tempRec);  
  107.   
  108.     system("pause");  
  109.     return 0;  
  110. }  

默认赋值操作符采用浅复制,即按位复制,当复制内容中存在指针变量时,需要定义自己的赋值操作符进行深复制;


四、友元操作符重载

1 .友元的概念

对于普通的类外函数f,要访问一个类A的私有成员和受保护成员是不可能的,除非将A的私有成员和受保护成员的访问权限改为public,但这样失去了类的封装作用,任何类外函数都可毫无拘束地使用其成员;但有时一个类外函数确实需要访问类的private或protected成员,因此在开放和封装之间折中,C++利用friend修饰符,设定类的友元,友元可对私有和受保护的成员进行操作。

友元使类外函数能直接访问类的私有和受保护数据,提供了程序设计时的灵活性,但同时也破坏了累的封装特性,因此使用友元要慎重!

类的友元可以使一个普通函数(非成员函数)、另一个类的成员函数、另一个完整的类;类的友元在类定义中使用friend保留字进行说明,在friend保留字后列出友元的名字(若友元为函数,则给出函数原型;若友元为类,则给出class类名);将另一个完整的类设为友元时,该类中所有成员函数都视为本类的友元函数。

举例:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. class House{  
  6. public:  
  7.     House(string name,string address)  
  8.     {  
  9.         House::name = name;  
  10.         House::address = address;  
  11.     }  
  12.     friend void showHouse(House& newHouse);  
  13. private:  
  14.     string name;  
  15.     string address;  
  16. };  
  17. void showHouse(House& newHouse)  
  18. {  
  19.     cout << newHouse.name << endl;  
  20.     cout << newHouse.address << endl;  
  21. }  
  22. int main()  
  23. {  
  24.     House clientHouse("YuQian""ZhongShan Road");  
  25.     showHouse(clientHouse);  
  26.   
  27.     system("pause");  
  28.     return 0;  
  29. }  

类House的定义中包含友元函数的声明:friend后紧跟函数showHouse的原型;

注意:showHouse并不是类House的成员函数,因此在函数定义时不能写成:

void House::showHouse(House& newHouse);

但该函数可访问类House的私有成员name和address。


2 .友元操作符重载

友元的另一个作用是操作符重载;

举例:

定义描述二维坐标(x,y)的类Pos,用友元函数实现+操作符的重载;

[cpp]  view plain  copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Pos{  
  5. public:  
  6.     Pos(float newPos_x = 0, float newPos_y = 0)  
  7.     {  
  8.         pos_x = newPos_x;  
  9.         pos_y = newPos_y;  
  10.     }  
  11.     void showPos()  
  12.     {  
  13.         cout << "x="<<pos_x << "\ty=" << pos_y << endl;  
  14.     }  
  15.     friend Pos operator + (Pos&, Pos&);  
  16.     // 重载+操作符的友元函数的声明  
  17. private:  
  18.     float pos_x;  
  19.     float pos_y;  
  20. };  
  21. Pos operator + (Pos& pos1, Pos& pos2)  
  22. // 友元函数的定义  
  23. {  
  24.     Pos temp;  
  25.     temp.pos_x = pos1.pos_x + pos2.pos_x;  
  26.     temp.pos_y = pos1.pos_y + pos2.pos_y;  
  27.     return temp;  
  28. }  
  29.   
  30. int main()  
  31. {  
  32.     Pos pos1(25, 50), pos2(1, 2);  
  33.     Pos pos3;  
  34.     cout << "Pos 1:" << endl;  
  35.     pos1.showPos();  
  36.     cout << "Pos 2:" << endl;  
  37.     pos2.showPos();  
  38.     pos3 = pos1 + pos2;  
  39.     cout << "Pos 1 + Pos 2:" << endl;  
  40.     pos3.showPos();  
  41.   
  42.     system("pause");  
  43.     return 0;  
  44. }  

分析:

程序中定义的类Pos描述一个二维坐标点,用友元函数重载+操作符,实现两个坐标点想家的操作:对两个坐标对象执行+运算,将两个坐标点的两个分量分别相加;

在主函数中,生命了三个坐标对象,pos_1, pos_2, pos_3,其中pos_1+pos_2被解释为对+操作符重载函数的调用;

上述操作符重载也可用成员函数来实现:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Pos{  
  5. public:  
  6.     Pos(float newPos_x = 0, float newPos_y = 0)  
  7.     {  
  8.         pos_x = newPos_x;  
  9.         pos_y = newPos_y;  
  10.     }  
  11.     void showPos()  
  12.     {  
  13.         cout << "x="<<pos_x << "\ty=" << pos_y << endl;  
  14.     }  
  15.     Pos operator + (Pos&);  
  16. private:  
  17.     float pos_x;  
  18.     float pos_y;  
  19. };  
  20. Pos Pos::operator + (Pos& anotherPos)  
  21. {  
  22.     Pos temp;  
  23.     temp.pos_x = pos_x + anotherPos.pos_x;  
  24.     temp.pos_y = pos_y + anotherPos.pos_y;  
  25.     return temp;  
  26. }  
  27.   
  28. int main()  
  29. {  
  30.     Pos pos1(25, 50), pos2(1, 2);  
  31.     Pos pos3;  
  32.     cout << "Pos 1:" << endl;  
  33.     pos1.showPos();  
  34.     cout << "Pos 2:" << endl;  
  35.     pos2.showPos();  
  36.     pos3 = pos1 + pos2;  
  37.     cout << "Pos 1 + Pos 2:" << endl;  
  38.     pos3.showPos();  
  39.   
  40.     system("pause");  
  41.     return 0;  
  42. }  

注意:友元操作符重载和成员函数操作符重载的不同在于:

a 一元操作符可实现不带参数的成员函数或带一个参数的友元函数;

b 二元操作符可实现带一个参数的成员函数或带两个参数的友元函数;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值