超载的增量(++)和递减(——)算子都是很简单的,用一个小的例外。其实有递增和递减运算符有两个版本:一个前缀增量和减量(如+ NX;——纽约;)和一个后置递增和递减(如NX + +;纽约——;)。
因为递增和递减运算符修改其操作数,他们最好的重载成员函数。我们将采取前缀版本的第一次因为他们最直接的。
重载前缀增量和减量
前缀增量和减量是重载的完全一样,任何正常的一元运算符。我们将做到这一点的例子:
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
class Digit
{
private:
int m_nDigit;
public:
Digit(int nDigit=0)
{
m_nDigit = nDigit;
}
Digit& operator++();
Digit& operator--();
int GetDigit() const { return m_nDigit; }
};
Digit& Digit::operator++()
{
// If our number is already at 9, wrap around to 0
if (m_nDigit == 9)
m_nDigit = 0;
// otherwise just increment to next number
else
++m_nDigit;
return *this;
}
Digit& Digit::operator--()
{
// If our number is already at 0, wrap around to 9
if (m_nDigit == 0)
m_nDigit = 9;
// otherwise just decrement to next number
else
--m_nDigit;
return *this;
}