正文

bool型的用法2007-07-18 16:40:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/wfxsky/27593.html

分享到:

布尔型对象可以被赋以文字值true 或false 例如// 初始化一个string 对象用来存放搜索的结果string search_word = get_word();// 把一个bool 变量初始化为falsebool found = false;string next_word;while ( cin >> next_word )if ( next_word == search_word )found = true;// ...// 缩写, 相当于: if ( found == true )if ( found )cout << "ok, we found the word\n";else cout << "nope, the word was not present.\n";虽然布尔类型的对象也被看作是一种整数类型的对象但是它不能被声明为signedunsigned short 或long 例如下列代码是非法的// 错误不能指定bool 为shortshort bool found = false;当表达式需要一个算术值时布尔对象(如found)和布尔文字都被隐式地提升成 int(正如下面的例子) false 变成0 而true 变成1 例如bool found = false;int occurrence_count = 0;while ( /* 条件省略 */ ){found = look_for( /* 内容省略 */ );// found 的值被提升为0 或者1occurrence_count += found;}正如文字false 和true 能自动转换成整数值0 和1 一样如果有必要算术值和指针值也能隐式地被转换成布尔类型的值0 或空指针被转换成false 所有其他的值都被转换成true例如// 返回出现次数extern int find( const string& );bool found = false;if ( found = find( "rosebud" ))// ok: found == true// 如找到返回该项的指针extern int* find( int value );if ( found = find( 1024 ))// ok: found == true

阅读(7705) | 评论(2)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册