類使用友元函數重載輸入(>>),輸出(

這篇文章,http://patmusing.blog.163.com/blog/static/135834960201001410555209/ ,很好的分析了爲什麼不使用成員函數來重載輸入、輸出符,而使用友元函數來重載輸入、輸出符。但是文章中有些錯誤,就是重載輸入>>時,不能將類類型定以爲const;而重載輸出<<時,可以將其定義爲類類型。代碼如下:

#include<iostream>
using namespace std;

class TestA{
    private:
        double a;
        double b;

    public:
        inline TestA():a(1),b(2){}
        inline TestA(int n,int c):a(n),b(c){}
        inline virtual ~TestA(){}

        friend istream& operator>>(istream&,TestA&);
        friend ostream& operator<<(ostream&,const TestA&);
};


istream& operator>>(istream& in, TestA& test){
    in >> test.a >> test.b;
    return in;
}

ostream& operator<<(ostream& out,const TestA& test){
    out << test.a << " " << test.b << endl;
    return out;
}

int main(){
    //TestA test1();
    TestA test2(3,4);
    TestA test3;

    cin >> test3;
    cout << test2 << test3;
    return 0;
}

如果在TestA類內定以爲:

friend istream& operator>>(istream&,const TestA&);

並且在函數外實現時也用了const,那麼會報錯。

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