布尔类型C++ 中的布尔类型C++ 在 C 语言的基础类型系统之上增加了 boolC++ 中的 bool 可取的值只有 true 和 false理论上 bool 只占用一个字节注意:true 代表真值,编译器内部用 1 表示;false 代表非真值,编译器内部用 0 表示。布尔类型的值bool 类型只有 true(非0) 和 false(0)两个值C++编译器会将非0值转换为 true, 0 转换为 false编程实验: 布尔类型的使用test_1.cpp#include <stdio.h>int main(){ bool b = 0; printf(“b = %d\n”, b); b++; printf(“b = %d\n”, b); b = b - 3; printf(“b = %d\n”, b); return 0;}输出:b = 0b = 1b = 1test_2.cpp#include <stdio.h>int main(){ bool b = false; int a = b; printf(“sizeof(b) = %d\n”, sizeof(b)); printf(“b = %d, a = %d\n”, b, a); b = 3; a = b; printf(“b = %d, a = %d\n”, b, a); b = -5; a = b; printf(“b = %d, a = %d\n”, b, a); a = 10; b = a; printf(“b = %d, a = %d\n”, b, a); a = 0; b = a; printf(“b = %d, a = %d\n”, b, a); return 0;}输出:sizeof(b) = 1b = 0, a = 0b = 1, a = 1b = 1, a = 1b = 1, a = 10b = 0, a = 0布尔类型是 C++ 中的基础类型可以定义 bool 类型的全局变量、局部变量可以定义 bool 类型的常量可以定义 bool 类型的指针可以定义 bool 类型的数组……三目运算符C++ 对三目运算符进行了升级下面的代码正确吗?void code(){ int a = 1; int b = 2; (a < b ? a : b) = 3; printf(“a = %d, b = %d\n”, a, b);}g++:编译无警告,无错误gcc:error: lvalue required as left operand of assignmentC 语言中的三目运算符返回的是变量值不能作为左值使用C++ 中的三目运算符可直接返回变量本身即可以作为左值使用,又可以作为右值使用注意:三目运算符可能返回的值中如果有一个常量值,则不能作为左值使用。C++ 中的引用变量名回顾变量是一段连续存储空间的别名程序中通过变量来申请并命名存储空间通过变量的名字可以使用存储空间问题:一段连续的存储空间只能有一个别名吗?在 C++ 中新增加了引用的概念引用可以看作一个已定义变量的别名引用的语法: Type& name = var;void code(){ int a = 4; int& b = a; // b 为 a 的别名 b = 5; // 操作 b 就是 操作 a}注意:普通引用在定义时必须用同类型的变量进行初始化实例分析: 引用初体验#include <stdio.h>int main(){ int a = 4; int& b = a; b = 5; printf(“a = %d\n”, a); printf(“b = %d\n”, b); printf("&a = %p\n", &a); printf("&b = %p\n", &b); return 0;}输出:a = 5b = 5&a = 0xbfea453c&b = 0xbfea453cint a;float& b = a;g++: error: invalid initialization of reference of type ‘float&’ from expression of type ‘int’float& b;g++: error: ‘b’ declared as reference but not initializedint& b = 1;g++: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’C++ 对三目运算符做了什么?当三目运算符的可能返回都是变量时,返回的是变量引用当三目运算符的可能返回中有常量时,返回的是值void code(){ int a = 1; int b = 2; (a < b ? a : b) = 3; // 正确,返回 a 或 b 的引用,可作为左值 (a < b ? 1 : b) = 3; // 错误,返回 1 或 b 的值,不能作为左值}小结bool 类型是 C++ 新增加的基础类型bool 类型的值只能是 true 和 falseC++ 中的三目运算符可作为左值使用C++ 中的引用可以看作变量的别名来使用三目运算符的可能返回都是变量时,返回的是引用以上内容参考狄泰软件学院系列课程,请大家保护原创!