要了解他们之间的差别,我首先分别输出他们的类型。
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
int main()
{
cout << typeid(true).name() << endl;
cout << typeid(TRUE).name() << endl;
}
这里编译报错,表示“TRUE”:未声明的标识符。
在代码段前面加上
#define TRUE (1)
之后,代码可以正常运行,得到的结果为:TRUE为int类型,而true为bool类型。
那么此时TRUE的值可否随着最初赋值而改变类型呢?答案是可以的。将宏定义代码改为:
#define TRUE (1.0)
最终得到的结果是:TRUE为double类型,而true为bool类型。
在进行一些了解后,我删除了#define函数,而是加入#include <windef.h>头文件,如下:
#include <iostream>
#include <windef.h>
#include <string>
#include <typeinfo>
using namespace std;
int main()
{
cout << typeid(true).name() << endl;
cout << typeid(TRUE).name() << endl;
}
在编译时出错,显示:
于是又在头文件最开始加入:#include <Windows.h>
#include <Windows.h>
解决报错,得到的结论为:TRUE为int类型,而true为bool类型。
(此处关于#include <Windows.h>:是Windows API的头文件,很大一部分API函数引用了它就能使用了)
那么又提出了新的问题,在进行运用时,可否将二者等同起来用呢?答案是可以的,一下代码中a的输出值为1,表示二者等同。
int a = true == TRUE;
cout << a << endl;
结论:true和false是c++中的关键字,可以直接调用,而True和FALSE则是通过#define或者头文件进行定义的。在对两者进行运用时,计算机会进行类型转换,所以在运用时差别不是很大。