C++ 重载运算符 重载 前置++,后置++

本文从WordPress迁移而来, 查看全部WordPress迁移文章

重载前置++,后置++

可通过成员函数重载或友员函数重载

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

class com{
friend bool check(com &obj);
//友员函数重载前置++
friend com & operator ++ (com &obj);
//友员函数重载后置++
friend com & operator ++ (com &obj,int);
private:
int a,b;
public:
com(){}
com(int aa,int bb):a(aa),b(bb){}

//成员函数重载前置++
com & operator ++ (){
a++; b++;
return *this;
}
//成员函数重载后置++
com & operator ++ (int){
com obj(*this);
a++;
b++;
return obj;
}

void reset(){
a = 0; b = 0;
}
void show(){
cout << a << " " << b << endl;
}
};

//友员函数前置++
com & operator ++ (com & obj){
++obj.a;
++obj.b;
return obj;
}
//友员函数后置++
com & operator ++ (com & obj , int){
com temp(obj);
obj.a++;
obj.b++;
return temp;
}

bool check(com &obj){
if(obj.a <= 5 && obj.b <= 5)
return true;
return false;
}

int main(){
com obj;

//调用成员函数前置++
obj.reset();
while( check( obj.operator++() ) ){
obj.show();
}

//调用成员 函数后置++
obj.reset();
while( check( obj.operator++(0) ) ){
obj.show();
}

//调用友员函数前置++
obj.reset();
while( check( operator++(obj) ) ){
obj.show();
}

//调用友员函数后置++
obj.reset();
while( check( operator++(obj,0) ) ){
obj.show();
}

//无论是成员函数 还是友员函数的调用,都可以直接写
//前置 ++obj
//后置 obj++
return 0;
}