8.9.2 重载递增和递减运算符
与本地C++(www.cppentry.com)相比,在C++(www.cppentry.com)/CLI中重载递增和递减运算符更加简单。只要我们将运算符函数实现为静态类成员,同一个函数就能既作为前缀又作为后缀运算符函数使用。下面是Length类递增运算符的实现:
- value class Length
- {
- public:
- // Code as before...
-
- // Overloaded increment operator function - increment by 1 inch
- static Length operator++(Length len)
- {
- ++len.inches;
- len.feet += len.inches/len.inchesPerFoot;
- len.inches %= len.inchesPerFoot;
- return len;
- }
- };
该版本的operator++()函数使长度递增1英寸。下面的代码可以练习该函数的使用:
- Length len = Length(1, 11); // 1 foot 11 inches
- Console::WriteLine(len++);
- Console::WriteLine(++len);
执行这段代码将产生下面的输出:
- 1 feet 11 inches
- 2 feet 1 inches
前缀和后缀递增操作使用的应该是Length类中同一个运算符函数,因此输出证实两者都能正确工作。之所以如此,是因为编译器能够确定是在递增操作数之前,还是在递增操作数之后在周围的表达式中使用该操作数的值,并据此相应地编译代码。