輸出流運算符的重載疑點


今天看到流運算符重載的時候有幾個疑問,一是爲何在只需聲明一次friend即可,而不是在兩個類之間都使用friend,二是爲何不能重載爲成員函數。


第一個問題:都使用friend,函數需要訪問兩個類的私有成員

第二個問題:重載爲了成員函數,但應用上出現了問題,詳情見代碼。




using std::ostream;
class a
{
public:


    ostream& operator<< (ostream & out)
    {
        out << x << y;
        return out;
    }
    
    

    friend ostream & operator<<(a & rhs, ostream & xout)
    {
        xout << rhs.x << rhs.y;
        return xout;
    }
    
    


    a(int s = 0, int q = 1)
        :x(s), y(q)        {    }

private:
    int x;
    int y;

};




int main()
{
        a b;
//     b.operator<<(std::cout);     //類的成員流運算符
//     std::cout << b;          //friend 流運算符重載
//     b << std::cout;          //friend 流運算符重載 或 成員流運算符的另一種形式
//     operator<<(b, std::cout);     //普通函數


    /*第一種<<的實現對1,3輸出均適用,
    1.  作爲a類的成員函數
    2.  1不可以寫爲2
    3.  1可以寫爲3
    4.  operator<< 函數未實現
    
    第二種<<的實現對3,4適用
    1. operator<<是普通函數,而非a的成員函數
    2. 位置反了
    3. 使用流運算符時,第一個參數在前
    4. 普通函數的使用,函數名加參數
    */
    return 0;
}


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