首页 > 代码库 > 实现一个整数类

实现一个整数类

注意点:

  1. 前++后++的区别。
  2. >>操作符注意处理输入失败的情形

代码:

 

 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 = http://www.mamicode.com/0);  // int -> Integer14     Integer &operator=(int data);15 16     Integer &operator++(); //++i17     Integer operator++(int); //i++18 19     operator int() //类型转化20     { return data_; }21 22 private:23     int data_;24 };25 26 27 #endif /* INTEGER_H_ */
View Code

 

 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);  //备份old41     ++data_;42 43     return temp;44 }45 46 Integer &Integer::operator=(int data)47 {48     data_ = data;49     return *this;50 }
View Code

 

实现一个整数类