C++operator

讓<<支持顯示一個對象。編寫輸出流操作符函數,左操作數的類型是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爲第二個參數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章