在c++中bool类型与整型之间存在着隐式转换,bool在存储之后隐式的转换为整型存储,其中true为1,false则为0。如果用整型给bool对象赋值,非零值为true,0则为false。
#include <iostream>
using namespace std;
int main()
{
bool t = true;
cout << "t is true: " << t << endl;
t = false;
cout << "t is false: " << t << endl;
t = 10 ;
if(t)
{
cout << "t is true: " << t << endl;
}
else
{
cout << "t is false: " << t << endl;
}
t = -10;
if(t)
{
cout << "t is true: " << t << endl;
}
else
{
cout << "t is false: " << t << endl;
}
t = 0;
if(t)
{
cout << "t is true: " << t << endl;
}
else
{
cout << "t is false: " << t << endl;
}
}
程序输出
t is true: 1
t is false: 0
t is true: 1
t is true: 1
t is false: 0
本文详细介绍了C++中bool类型与整型之间的隐式转换规则。当bool类型的变量被赋值为非零整数时,其值会被视为true;而赋值为0时,则被视为false。此外,当整型数值被赋予bool变量时,非零值会转换为true,0则转换为false。文章通过具体示例代码展示了这一转换过程及其在条件判断中的应用。
4098

被折叠的 条评论
为什么被折叠?



