-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path++i_i++.cpp
105 lines (83 loc) · 1.97 KB
/
++i_i++.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
using namespace std;
class Point{
int x_;
int y_;
public:
Point(int x = 0, int y = 0) {
x_ = x;
y_ = y;
cout << "this is constructor" << endl;
}
Point(const Point& b) {
this->x_ = b.x_;
this->y_ = b.y_;
cout << "this is copy constructor" << endl;
}
~Point() {
cout << "this is destructor" << endl;
}
Point& operator++(); // 前置
const Point operator++(int); // 后置
Point operator+(const Point& _right) {
Point temp; // a = a + b 第一次调用构造函数
temp.x_ = this->x_ + _right.x_;
temp.y_ = this->y_ + _right.y_;
return temp; // a = a + b 第二次调用构造函数
}
Point& operator+=(const Point& _right) {
this->x_ += _right.x_;
this->y_ += _right.y_;
return *this;
}
void DisplayPoint();
};
Point& Point::operator++()
{
++x_;
++y_;
return *this;
}
const Point Point::operator++(int)
{
Point temp(*this); // i++ 这里就需要调用构造函数
this->x_++;
this->y_++;
return temp; // i++ 这里也需要调用构造函数
}
void Point::DisplayPoint()
{
cout << "x: " << this->x_ << endl;
cout << "y: " << this->y_ << endl;
}
int main()
{
Point a(1,1);
cout << endl << "this is a++: " << endl;
a ++;
cout << endl << "this is ++a: " << endl;
++ a;
Point b(2, 2);
Point* c;
cout << endl << "this is &b: " << &b << endl;
cout << endl << "this is c = &(++b): ";
c = &(++b);
cout << c << endl;
// 这里会报错,b++不能作为左值而被取地址
// cout << endl << "this is c = &(b++): ";
// c = &(b++);
// cout << c << endl;
}
/*
结果输出:
this is constructor
this is a++:
this is copy constructor
this is destructor
this is ++a:
this is constructor
this is &b: 0x7ffeee9e7618
this is c = &(++b): 0x7ffeee9e7618
this is destructor
this is destructor
*/