讓<<支持顯示一個對象。編寫輸出流操作符函數,左操作數的類型是ostream,所以這個函數必須是全局的,爲了訪問poin私有對象,聲明爲point類的友元函數。如下:
class point{
public:int x;
private:
int y;
public:
point(int x,int y){this->x=x;this->y=y;}
point(){x=0;y=0;}
point &operator=(const point &other){
this->x=other.x;
this->y=other.y;
return *this;
}
friend ostream &operator<<(ostream &os,point &pt);
};
ostream &operator<<(ostream &os,point &pt){
os<<pt.x<<" "<<pt.y<<endl;
return os;
}
int main(){
point n(2,3);;
point p=n;
cout<<p;
}
結果:2 3
cout作爲第一個參數傳入,p爲第二個參數。