操作符重載一般有以下幾點需要注意的:
1)重載操作符必須有一個類類型的操作數,這是爲了避免對已有的內置類型對象的操作符的原本含義的更改;
2)重載後的操作符的優先級和結合性是固定不變的;
3)重載操作符爲類成員函數時,它的形參表中會少一個形參,原因是有一個隱含形參this,而且該this形參限定爲第一個操作數;
4)當操作符爲非類成員函數的時候,如果該函數需要訪問類的私有數據成員,需要將該操作符設置爲友元。
下面主要介紹介個常用的操作符重載模式以及需要注意的問題
一、輸出操作<<的重載
其函數原型是
ostream& operator<<(ostream& os, const Classtype &object) {
os<<object.(數據成員名);
return os;
}
針對上面的操作符重載,我們給出以下解釋:
該操作符重載的第一個形參類型是ostream&,原因是ostream對象不能複製,因此選擇引用,ostream對象同樣不能是const的,因爲寫入到流通長會改變流的狀態。第二個形參爲const Classtype的應用,原因是爲了避免類對象的複製,同時輸出操作不應該對對象的數據成員做修改,所以應該聲明爲const的。另外輸出操作符要儘可能少的做格式化,而且IO操作符必須爲非類成員函數,主要是爲了和目前所用的形式統一,通常將其設置爲類的友元。返回值類型是ostream& 類型個人認爲主要是爲了使用方便,適用於連寫的這種方式,比如cout<<object1<<object2.........
#include <iostream>
#include <string>
using namespace std;
class student{
public:
student():a(0),s("Hello"){};
student(int c,string s1):a(c),s(s1){};
student& student::operator=(student &stu)
{
this->a=stu.a;
this->s=stu.s;
return *this;
}
/*friend
void operator<<(ostream& out,const student &stu)
{
out<<stu.a<<"\t"<<stu.s;
}*/
friend
ostream& operator<<(ostream& out,const student &stu)
{//注意此處的形參,out不可以爲const。
out<<stu.a<<"\t"<<stu.s;
return out;
}
friend
istream& operator>>(istream& in,student &stu)
{//返回值必須爲引用,且類形參爲非const,因爲要對其寫入。
in>>stu.a>>stu.s;
return in;
}
private:
int a;
string s;
};
int main()
{
student ab(3,"I miss you");
student stu1,stu2;
stu1=stu2=ab;//=操作符返回值,可以爲引用或者非引用,因爲操作順序是從右向做操作的。
cout<<stu1;//即使<<操作符返回值爲空值,也可以這麼進行輸出。但是如果想連續輸出
//就像cout<<stu1<<stu2;就必須使用返回值爲ostream &的版本了,而且此時的返回值必須爲引用。。
//因爲操作的順序是從左到右,返回的引用,還可以對其賦值。如果返回非引用,ostream對象沒有辦法複製
cin>>stu1;
cout<<stu1;
return 1;
}