首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 基礎

C++ 重載輸入輸出運算符 (>>/<<):實現類與串流的無縫整合

     編輯:C++ 基礎

為什麼要重載 << / >>?

C++ 標準庫已為內建型別(int、double、string 等)重載串流運算符。但自定義類型若要支援 cout << obj、cin >> obj 這種直觀語法,必須自行重載。目標是讓自訂類型擁有與內建型別一致的 I/O 體驗。

核心原則:必須為全域函數

因為左操作數是串流物件(ostream/istream),無法作為成員函數(那需要修改標準庫類)。因此只能以全域函數(通常聲明為友元)重載。

重載輸出運算符 operator<<

ostream& operator<<(ostream& out, const Complex& c) {
    out << c.m_real << " + " << c.m_imag << " i";
    return out;  // 返回引用支援鏈式輸出
}
  • 第一參數:ostream&(輸出串流引用)
  • 第二參數:const Complex&(常量引用,不修改物件)
  • 返回:ostream&,實現 cout << a << b
  • 需在類內聲明為 friend 以訪問 private 成員

重載輸入運算符 operator>>

istream& operator>>(istream& in, Complex& c) {
    in >> c.m_real >> c.m_imag;
    return in;  // 返回引用支援鏈式輸入
}
  • 第二參數:Complex&(非常量引用,需修改物件)
  • 返回:istream&,實現 cin >> a >> b
  • 同樣需聲明為 friend

完整實戰:復數類完整 I/O 支援

#include <iostream>
using namespace std;

class Complex {
public:
    Complex() : m_real(0), m_imag(0) {}
    Complex(double r, double i) : m_real(r), m_imag(i) {}

    // 算術運算符重載(全域友元)
    friend Complex operator+(const Complex&, const Complex&);
    friend Complex operator-(const Complex&, const Complex&);
    friend Complex operator*(const Complex&, const Complex&);
    friend Complex operator/(const Complex&, const Complex&);

    // I/O 運算符重載(全域友元)
    friend istream& operator>>(istream&, Complex&);
    friend ostream& operator<<(ostream&, const Complex&);

private:
    double m_real, m_imag;
};

// I/O 實現
istream& operator>>(istream& in, Complex& c) {
    in >> c.m_real >> c.m_imag;
    return in;
}
ostream& operator<<(ostream& out, const Complex& c) {
    out << c.m_real << " + " << c.m_imag << " i";
    return out;
}

// 算術實現略...

int main() {
    Complex c1, c2, c3;
    cin >> c1 >> c2;  // 輸入: 2.4 3.6  4.8 1.7
    c3 = c1 + c2;  cout << "c1 + c2 = " << c3 << endl;
    c3 = c1 - c2;  cout << "c1 - c2 = " << c3 << endl;
    c3 = c1 * c2;  cout << "c1 * c2 = " << c3 << endl;
    c3 = c1 / c2;  cout << "c1 / c2 = " << c3 << endl;
}

運行結果

2.4 3.6
4.8 1.7
c1 + c2 = 7.2 + 5.3 i
c1 - c2 = -2.4 + 1.9 i
c1 * c2 = 5.4 + 21.36 i
c1 / c2 = 0.942308 + 0.705128 i

關鍵設計要點總結

項目operator>>operator<<
第一參數istream&ostream&
第二參數Type& (可修改)const Type& (唯讀)
返回型別istream&ostream&
鏈式調用cin >> a >> bcout << a << b
友元聲明必要 (訪問 private)必要 (訪問 private)

常見陷阱與最佳實踐

  1. 格式控制:輸出時考慮 iomanip 格式化,輸入時處理空白、分隔符
  2. 錯誤狀態:檢查串流狀態 in.fail(),異常輸入時保持物件有效
  3. 二進制序列化:大量資料考慮二進制讀寫而非文本格式
  4. 避免修改全域格式旗標:使用 ios::fmtflags 保存/恢復

總結

重載 <</>> 讓自定義類型融入 C++ 串流生態,實現與內建型別一致的 I/O 體驗。核心在於:全域函數、友元聲明、引用參數、引用返回、const 正確性。這是構建專業級 C++ 類庫的基礎技能之一。

  1. 上一篇文章:
  2. 下一篇文章:
  • --热点文章
  • Copyright © 程式碼之家 All Rights Reserved