自增自减: operator++()
、operator++(int)
#
一般地, 先定义 前置 版本, 再基于前置版本定义后置版本:
1class Widget {
2 public:
3 // 前置自增
4 Widget& operator++() {
5 ++value_;
6 return *this;
7 }
8
9 // 后置自增
10 Widget operator++(int) {
11 Widget old(*this); // 复制旧值
12 ++*this; // 调用前置自增
13 return old; // 返回旧值
14 }
15
16 private:
17 int value_;
18};
如果你定义了 operator+=
, 可以用它定义前置自增:
1class Widget {
2 public:
3 Widget& operator+=(int value) {
4 value_ += value;
5 return *this;
6 }
7
8 Widget& operator++() {
9 *this += 1;
10 return *this;
11 }
12
13 Widget operator++(int) {
14 Widget old(*this); // 复制旧值
15 ++*this; // 调用前置递增
16 return old; // 返回旧值
17 }
18
19 private:
20 int value_;
21};