标签:style blog http io color ar os sp div
注意点:
>>操作符注意处理输入失败的情形
代码:
1 #ifndef INTEGER_H_ 2 #define INTEGER_H_ 3 4 #include <iostream> 5 6 class Integer 7 { 8 9 friend std::ostream &operator<< (std::ostream &os, const Integer &i); 10 friend std::istream &operator>> (std::istream &is, Integer &i); 11 12 public: 13 Integer(int data = 0); // int -> Integer 14 Integer &operator=(int data); 15 16 Integer &operator++(); //++i 17 Integer operator++(int); //i++ 18 19 operator int() //类型转化 20 { return data_; } 21 22 private: 23 int data_; 24 }; 25 26 27 #endif /* INTEGER_H_ */
1 #include "Integer.h" 2 3 using namespace std; 4 5 6 Integer::Integer(int data) 7 :data_(data) 8 { 9 } 10 11 ostream &operator<< (ostream &os, const Integer &i) 12 { 13 return os << i.data_; 14 } 15 16 istream &operator>> (istream &is, Integer &i) 17 { 18 int temp = i.data_; //backup; 19 is >> i.data_; 20 if(!is) //输入失败 21 { 22 i.data_ = temp; //还原 23 } 24 25 return is; 26 } 27 28 29 Integer &Integer::operator++() 30 { 31 //++i = 5; 32 ++data_; 33 34 return *this; 35 } 36 37 Integer Integer::operator++(int) 38 { 39 //i++ 不能为左值 40 Integer temp(*this); //备份old 41 ++data_; 42 43 return temp; 44 } 45 46 Integer &Integer::operator=(int data) 47 { 48 data_ = data; 49 return *this; 50 }
标签:style blog http io color ar os sp div
原文地址:http://www.cnblogs.com/xzyline/p/4076382.html