如同您可以 重載 << 運算子 以直接輸出物件資訊,您也可以重載 >> 運算子,將輸入的資訊直接指定給物件,重載 >> 運算子的語法如下:
istream &operator>>(istream &s, class-name &ob) {
// 實作
return s;
}
注意第二個參數必須是參考,這樣才可以將資訊指定給所要的物件,而不是一個複製物件;同樣的,重載 >> 運算子多是利用friend函式進行,下面這個程式是個簡單的例子:
#include <iostream> using namespace std;
class Point { int x, y; public: Point() { x = y = 0; }
Point(int x, int y) { this->x = x; this->y = y; }
friend istream &operator>>(istream &s, Point &p); friend ostream &operator<<(ostream &s, Point p); };
istream &operator>>(istream &s, Point &p) { cout << "輸入點座標: "; s >> p.x >> p.y; return s; }
ostream &operator<<(ostream &s, Point p) { s << "("<< p.x << ", " << p.y << ")"; return s; }
int main() { Point p1;
cin >> p1; cout << "p1: " << p1 << endl;
return 0; }
執行結果:
輸入點座標: 20 10
p1: (20, 10) |
|
|