1. 程式人生 > >C++結構體的建構函式以及運算子的過載

C++結構體的建構函式以及運算子的過載

由於結構體經常用到,所以對結構體的用法做了一下整理

#include<iostream>
using namespace std;
struct node
{
    int x,y;
    static const int BASC=10000;   //定義靜態成員變數
    node(int x=0,int y=0):x(x),y(y){}   //建構函式
    //過載輸出流
    friend ostream& operator<<(ostream&out,const node &p)
    {
        out<<p.x<<" "<<p.y<<endl;
        return out;
    }
    //過載輸入流,不能為const
    friend istream&operator>>(istream&in,node &p)
    {
        in>>p.x>>p.y;
        return in;
    }
    //過載<,成員函式
    bool operator<(const node&p)const
    {
        return x<p.x;
    }
    //過載>友元函式
    friend bool operator>(const node &a,const node &b)
    {
        return a.x>b.x;
    }
    //過載+,呼叫建構函式
    friend node operator+(const node&a,const node&b)
    {
        return node(a.x+b.x,a.y+b.y);
    }

};
int main()
{
    int x;
    node a(1,2),b(3,4);    //初始化
    cout<<a<<b;
    cout<<(a>b)<<endl<<(a<b)<<endl;
    cout<<a+b;
    cout<<node::BASC<<endl;    //訪問結構體的靜態成員變數
    while(cin>>a)
    {
        cout<<a;
    }
    return 0;
}

其中值得注意的是對於流的過載,ostream後的&儘量加上

如果寫成這樣   ostream operator << (ostream& os, Point& pt) 
則:
Point a, b;
cout<<a<<b;
錯誤,只能寫為:
cout<<a;
cout<<b;
原因在於
cout<<a<<b;
相當於:
(cout<<a)<<b;
第一個()中返回cout的臨時變數,它可以不可以作為左值。因而錯誤。
如果寫成:  ostream& operator << (ostream& os, Point& pt) 
則:
cout<<a<<b;
正確,因為它等同於
(cout<<a)<<b;
(acout<<a)返回cout的引用,即就是它自己,它可以再次作為左值。因而能夠連著寫這個輸出流