C++ 輸入/輸出運算符重載
C++ 能夠使用流提取運算符 >> 和流插入運算符 << 來輸入和輸出內置的數據類型。您可以重載流提取運算符和流插入運算符來操作對象等用戶自定義的數據類型。
在這裏,有一點很重要,我們需要把運算符重載函數聲明為類的友元函數,這樣我們就能不用創建對象而直接調用函數。
下麵的實例演示了如何重載提取運算符 >> 和插入運算符 <<。
實例
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 到無窮
int inches; // 0 到 12
public:
// 所需的構造函數
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