increment/decrement/dereference

 

 1 #include <vector>
 2 #include <deque>
 3 #include <algorithm>
 4 #include <iostream>
 5 #include <ostream>
 6 #include <iterator>
 7 using namespace std;
 8 
 9 class INT
10 {
11     friend ostream& operator<<(ostream &os, const INT& i);
12 public:
13     INT(int i) : m_i(i){}
14     //prefix:increment and then fetch
15     INT& operator ++()
16     {
17         ++(this->m_i);//随着class的不同,该行应该有不同的操作
18         return *this;
19     }
20 
21     //postfix:fetch and then increment
22     const INT operator ++(int)
23     {
24         INT temp = *this;
25         ++(*this);
26         return temp;
27     }
28 
29     //prefix:decrement and then fetch
30     INT& operator --()
31     {
32         --(this->m_i);
33         return *this;
34     }
35 
36     //postfix:fetch and then decrement
37     const INT operator --(int)
38     {
39         INT temp = *this;
40         --(*this);
41         return temp;
42     }
43 
44     //dereference
45     int& operator*() const
46     {
47         return (int&)m_i;
48     }
49 
50 private:
51     int m_i;
52 };
53 
54 ostream& operator<<(ostream& os, const INT& i)
55 {
56     os << '[' << i.m_i << ']';
57     return os;
58 }
59 
60 int main( )
61 {
62     INT i(5);
63     cout << i++ << endl;
64     cout << ++i << endl;
65     cout << i-- << endl;
66     cout << --i << endl;
67     cout << *i << endl;
68     return 0;
69 }

Output:

[5]
[7]
[7]
[5]
5
posted @ 2017-04-06 12:31  PKICA  阅读(287)  评论(0编辑  收藏  举报