要点:指针类型和算术值都可以隐式转换为bool类型(参考:C++ Primer P156-157)
实例:(VS2008)
#include <iostream>
using namespace std;
bool foo(bool flag)
{
return flag;
}
int main()
{
cout<<foo("hello world")<<endl; //pointer to bool
cout<<foo(6)<<endl; //arithmetic to bool
char *p="good";
cout<<foo(p)<<endl; //pointer to bool
p=NULL;
cout<<foo(p)<<endl; //pointer to bool
char c='a';
cout<<foo(c)<<endl; //arithmetic to bool
c='\0';
cout<<foo(c)<<endl; //arithmetic to bool
system("pause");
return 0;
}
output: 1 1 1 0 1 0
(1)如果指针或算术值为0,则其bool值为false,而其他值为true.
(2)同样可将bool对象转换为int型。零转换为false,,而其他值则转换为true。 将bool对象转换为算术类型时,true变为1,而false变为0。