cpp i++ vs ++i

cpp i++ vs ++i

Guide

code

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
using namespace std;

class Integer
{
public:
Integer(int value): v(value)
{
cout << "default constructor" << endl;
}
Integer(const Integer &other)
{
cout << "copy constructor" << endl;
v = other.v;
}
Integer &operator=(const Integer &other)
{
cout << "copy assignment" << endl;
v = other.v;
return *this;
}

// ++i first +1,then return new value
Integer &operator++()
{
cout << "Integer::operator++()" << endl;
v++;
return *this;
}

// i++ first save old value,then +1,last return old value
Integer operator++(int)
{
cout << "Integer::operator++(int)" << endl;
Integer old = *this;
v++;
return old;
}

void output()
{
cout << "value " << v << endl;
}
private:
int v;
};

void test_case()
{
Integer obj(10);
Integer obj2 = obj;
Integer obj3(0);
obj3 = obj;
cout << "--------------" << endl;
cout << "++i" << endl;
++obj;
obj.output();
cout << "i++" << endl;
obj++;
obj.output();
}

int main()
{
test_case();
return 0;
}

output

default constructor
copy constructor
default constructor
copy assignment
--------------
++i
Integer::operator++()
value 11
i++
Integer::operator++(int)
copy constructor
value 12

Reference

History

  • 2019/11/08: created.

Copyright

坚持技术分享,您的支持将鼓励我继续创作!