Ray's playground

 

Item 6:Distinguish between prefix and postfix forms of increment and decrement operators.(More Effective C++)

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class MyInt
 5 {
 6 private:
 7     int a;
 8 public:
 9     MyInt(int n) : a(n){};
10 
11     MyInt& operator++()
12     {
13         a += 1;
14         return *this;
15     };
16     
17     const MyInt operator++(int)
18     {
19         MyInt old = *this;
20         ++(*this);
21 
22         return old;
23     };
24 
25     int getValue()
26     {
27         return a;
28     }
29 };
30 
31 int main()
32 {
33     MyInt i(4);
34 
35     MyInt j = i++;
36     cout << j.getValue() << endl;
37     cout << (++i).getValue() << endl;
38 
39     cin.get();
40 }

posted on 2011-06-10 22:32  Ray Z  阅读(227)  评论(0编辑  收藏  举报

导航