-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoperators.cpp
More file actions
101 lines (72 loc) · 2.87 KB
/
operators.cpp
File metadata and controls
101 lines (72 loc) · 2.87 KB
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
#include <iostream>
#include <cmath>
class X {
public:
X(double value) : d(value) { }
double getValue() const { return d; }
// pre-increment operator
// Возвращается ссылка на объект после прибавления
X& operator++() {
move(1);
return (*this);
}
// post-increment operator
// Возвращается значение объекта до прибавления
// int в аргументе -- просто для того, чтобы различать с пре-инкрементом
X operator++(int) {
X answer(*this);
++(*this);
return answer;
}
// Обратите внимание -- везде повторное использование кода,
// которое к тому же гарантирует корректность наших операций,
// то есть x += b и x = x + b -- это одно и то же.
X& operator+=(const X& rhs) {
move(rhs.getValue());
return *this;
}
friend X operator+(X lhs, const X& rhs) {
lhs += rhs;
return lhs;
}
// А как бы вы реализовали вариант с минусом?
// Всегда, когда определена какая-то часть операторов сравнения,
// все они должны сводиться к одному (иначе напишите функцию)
friend bool operator< (const X& lhs, const X& rhs) { return lhs.d < rhs.d; }
friend bool operator!=(const X& lhs, const X& rhs) { return rhs < lhs || lhs < rhs; }
friend bool operator==(const X& lhs, const X& rhs) { return ! (lhs != rhs); }
friend bool operator> (const X& lhs, const X& rhs) { return rhs < lhs; }
friend bool operator<=(const X& lhs, const X& rhs) { return ! (lhs > rhs); }
friend bool operator>=(const X& lhs, const X& rhs) { return ! (lhs < rhs); }
// Всегда, когда оператор не делает в точности то и только то,
// что от него подразумевается, заместо него надо делать функцию
friend bool approximatelyEqual(const X& lhs, const X& rhs) {
return fabs(lhs.d - rhs.d) < 1e-14;
}
private:
double d;
void move(double change) { d = d + change; }
};
int main() {
X a(0);
std::cout << a.getValue() << std::endl;
a++;
std::cout << a.getValue() << std::endl;
++a;
std::cout << a.getValue() << std::endl;
std::cout << "--------------" << std::endl;
X b(0);
std::cout << b.getValue() << std::endl;
std::cout << (++b).getValue() << std::endl;
std::cout << b.getValue() << std::endl;
std::cout << (b++).getValue() << std::endl;
std::cout << b.getValue() << std::endl;
std::cout << "--------------" << std::endl;
// Хороший повод для убийства
/*
X c(0);
std::cout << (c++ + ++c + c++).getValue() << std::endl;
std::cout << c.getValue() << std::endl;
*/
return 0;
}