Chinaunix首页 | 论坛 | 博客
  • 博客访问: 407429
  • 博文数量: 101
  • 博客积分: 2207
  • 博客等级: 大尉
  • 技术积分: 2508
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-19 20:45
文章分类

全部博文(101)

文章存档

2013年(15)

2012年(86)

我的朋友

分类: C/C++

2012-07-29 19:51:21

Member functions of the form

operator TypeName()

are conversion operators. They allow objects of the class type to be used as if they were of typeTypeName and when they are, they are converted to TypeName using the conversion function.

In this particular case, operator bool() allows an object of the class type to be used as if it were abool. For example, if you have an object of the class type named obj, you can use it as

if (obj)

This will call the operator bool(), return the result, and use the result as the condition of the if.

It should be noted that operator bool() is A Very Bad Idea and you should really never use it. For a detailed explanation as to why it is bad and for the solution to the problem, see "The Safe Bool Idiom."

(C++0x, the forthcoming revision of the C++ Standard, adds support for explicit conversion operators. These will allow you to write a safe explicit operator bool() that works correctly without having to jump through the hoops of implementing the Safe Bool Idiom.)

阅读(727) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~