1. 程式人生 > >C++ 檔案流fstream的過載

C++ 檔案流fstream的過載

#include<fstream> 
#include<iostream>
using namespace std; 
////////////////////////////////////////////////
class PhoneNumber;
ofstream &operator<<(ofstream &,const PhoneNumber &); 
ifstream &operator>>(ifstream &,PhoneNumber &); 
////////////////////////////////////////////////
class PhoneNumber 
{ 
public: 
 string areacode; 
 string exchange; 
 int line; 
}; 

ofstream &operator<<(ofstream &output,PhoneNumber &num) 
{ 
 output<<"("<<num.areacode<<")"<<num.exchange<<"-"<<num.line; 
 return output; 
} 
ifstream &operator>>(ifstream &input,PhoneNumber &num) 
{ 
 input>>num.areacode;
 input>>num.exchange;
 input>>num.line;

 cout << num.areacode << endl ;
 cout << num.exchange << endl ;
 cout << num.line << endl ;
 
 return input; 
} 

int main() 
{ 
 PhoneNumber phone; 
 ifstream fcin("streamOverloadInput.txt") ;
 ofstream fcout("streamOverloadOutput.txt") ;
 fcout<<"輸入一個電話號碼:"; 
 fcin>>phone; 
 fcout<<phone <<endl; 
 fcin>>phone ;
 fcout<<phone; 
 return 0 ;
}