省流

  • 前置递增(递减)返回引用,后置递增(递减)返回值

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
using namespace std;

class myInt {
friend ostream& operator<< (ostream &cout,myInt myint);
public:
myInt() {
m_Num = 0;
}
//前置递增
myInt& operator++() {
m_Num++;//先进行++运算
return *this;//再将自身返回
}
//后置递增
myInt operator++(int) {
myInt temp = *this;//先记录结果
m_Num++;//再递增
return temp;//返回记录结果
}

//前置递减
myInt &operator--() {
m_Num--;
return *this;
}
//后置递减
myInt operator--(int) {
myInt temp = *this;//先记录
m_Num--;//再递减
return temp;//最后返回
}

private:
int m_Num;
};

ostream &operator<< (ostream &cout,myInt myint) {
cout << myint.m_Num;
return cout;
}

void test1() {
myInt myint;
cout << "递增" << endl;
cout << ++myint << endl;
cout << myint++ << endl;
cout << myint << endl;
}
void test2() {
myInt myint;
cout << "递减" << endl;
cout << --myint << endl;
cout << myint-- << endl;
cout << myint << endl;
}

int main(){
test1();//递增
test2();//递减
return 0;
}