首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 運算符重載:流插入運算符 << 正確實現模式

     編輯:程式設計綜合問答

問題代碼分析

ostream operator<< (ostream &os, R &r) {
    os << r.n << ',' << r.d;
    return os; // 報錯
}

錯誤原因:

  1. 返回類型應為 ostream&(引用),而非 ostream(值拷貝)。ostream 禁止拷貝構造
  2. 參數 R &r 應為 const R &r,因輸出操作不應修改對象
  3. 非成員函數重載 operator<< 通常需聲明為 友元函數 以訪問私有成員

標準實現模式

class Test {
public:
    int a, b;
    Test() : a(0), b(0) {}
    Test(int a, int b) : a(a), b(b) {}

    // 友元函數聲明(類內部)
    friend ostream& operator<<(ostream& os, const Test& t);
    friend istream& operator>>(istream& is, Test& t);
};

// 類外部實現
ostream& operator<<(ostream& os, const Test& t) {
    os << "a = " << t.a << endl;
    os << "b = " << t.b << endl;
    return os; // 返回引用,支持鏈式調用
}

istream& operator>>(istream& is, Test& t) {
    is >> t.a >> t.b;
    return is;
}

關鍵點總結

項目正確寫法說明
返回類型ostream&流對象不可拷貝,必須返回引用
第一參數ostream& os流對象引用
第二參數const T& obj常引用,保證只讀
訪問私有成員聲明 friend非成員函數訪問私有數據必須友元
鏈式調用return os;支持 cout << a << b;

修正後的用戶代碼

class R {
public:
    int n, d;
    R(int a, int b) : n(a), d(b) {}

    friend ostream& operator<<(ostream& os, const R& r);
};

ostream& operator<<(ostream& os, const R& r) {
    os << r.n << ',' << r.d;
    return os;
}

int main() {
    R a(2,3), b(4,5);
    cout << a << b; // 輸出: 2,34,5
    return 0;
}

進階提示

  • 若類繼承自標準流相關基類,需注意虛函數重載規則
  • 格式化輸出可考慮使用 iomanip 控制寬度、精度等
  • 輸入運算符 operator>> 同理,第二參數為非 const 引用(需修改對象)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved