bool类型

 

bool型的用法(2007-7-18 16:40:00)

【收藏】 【评论】 【打印】 【关闭】

标签:C\C++ VC

布尔型对象可以被赋以文字值true 或false 例如
// 初始化一个string 对象用来存放搜索的结果
string search_word = get_word();
// 把一个bool 变量初始化为false
bool 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";
虽然布尔类型的对象也被看作是一种整数类型的对象但是它不能被声明为signed
unsigned short 或long 例如下列代码是非法的
// 错误不能指定bool 为short
short bool found = false;
当表达式需要一个算术值时布尔对象(如found)和布尔文字都被隐式地提升成 int(正
如下面的例子) false 变成0 而true 变成1 例如
bool found = false;
int occurrence_count = 0;
while ( /* 条件省略 */ )
{
found = look_for( /* 内容省略 */ );
// found 的值被提升为0 或者1
occurrence_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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值