C++輸入/輸出運算符重載
C++是能夠輸入和輸出內置用流提取運算>>和流插入運算符<<數據類型。流插入和流提取運算符也可以被重載以執行輸入和輸出用於用戶定義的像的對象的類型。
這裡,重要的是使運算符重載函數的一個友元類,因為這將不用創建一個對象而被調用。
下麵的例子說明了提取運算符>>和插入運算符<<是如何操作的。
#include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } friend ostream &operator<<( ostream &output, const Distance &D ) { output << "F : " << D.feet << " I : " << D.inches; return output; } friend istream &operator>>( istream &input, Distance &D ) { input >> D.feet >> D.inches; return input; } }; int main() { Distance D1(11, 10), D2(5, 11), D3; cout << "Enter the value of object : " << endl; cin >> D3; cout << "First Distance : " << D1 << endl; cout << "Second Distance :" << D2 << endl; cout << "Third Distance :" << D3 << endl; return 0; }
讓我們編譯和運行上麵的程序,這將產生以下結果:
$./a.out Enter the value of object : 70 10 First Distance : F : 11 I : 10 Second Distance :F : 5 I : 11 Third Distance :F : 70 I : 10