increment/decrement/dereference操作符

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