设为首页 加入收藏

TOP

8.9.2 重载递增和递减运算符
2013-10-07 12:36:02 来源: 作者: 【 】 浏览:74
Tags:8.9.2 重载 递增 递减 运算

8.9.2  重载递增和递减运算符

与本地C++(www.cppentry.com)相比,在C++(www.cppentry.com)/CLI中重载递增和递减运算符更加简单。只要我们将运算符函数实现为静态类成员,同一个函数就能既作为前缀又作为后缀运算符函数使用。下面是Length类递增运算符的实现:

  1. value class Length  
  2. {  
  3. public:  
  4. // Code as before...  
  5.  
  6. // Overloaded increment operator function - increment by 1 inch  
  7. static Length operator++(Length len)  
  8. {  
  9. ++len.inches;  
  10. len.feet += len.inches/len.inchesPerFoot;  
  11. len.inches %= len.inchesPerFoot;  
  12. return len;  
  13. }  
  14. }; 

该版本的operator++()函数使长度递增1英寸。下面的代码可以练习该函数的使用:

  1. Length len = Length(1, 11);         // 1 foot 11 inches  
  2. Console::WriteLine(len++);  
  3. Console::WriteLine(++len); 

执行这段代码将产生下面的输出:

  1. 1 feet 11 inches  
  2. 2 feet 1 inches 

前缀和后缀递增操作使用的应该是Length类中同一个运算符函数,因此输出证实两者都能正确工作。之所以如此,是因为编译器能够确定是在递增操作数之前,还是在递增操作数之后在周围的表达式中使用该操作数的值,并据此相应地编译代码。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇8.9.4 实现引用类型的赋值运算符 下一篇8.9.1 在数值类中重载运算符(2)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: