🔷 第二章 C++语言基础
📄 一句话概括

bool 是"真/假"类型,只有两个值:true 和 false——它们是 C++ 的关键字。它占 1 字节(不是 1 位),里面存的其实还是 1 和 0。bool 的主要来源是比较运算(3 > 2 得 true)和逻辑运算(&& \|\| !),主要去处是判断条件(第 4 章 if、while 的主角)。

一、bool 的基本用法

bool isFound = false;        // 还没找到
bool hasError = true;        // 出错了
bool ok = (3 > 2);           // 比较运算的结果就是 bool
true false
内存里的值 1 0
含义 成立 / 有 / 成功 不成立 / 没有 / 失败
占字节 1 1

为什么是 1 字节不是 1 位:C++ 里最小的可寻址单位是字节,没法单独操作"一个位"(要做位运算得专门的技术)。

二、它从哪来、到哪去

来源(都产生 bool):

bool a = (5 > 3);            // 比较:true
bool b = (5 == 3);           // 相等比较:false
bool c = (5 > 3) && (2 > 1); // 逻辑与:true
bool d = !a;                 // 逻辑非:false

去处(主要用途):

if (isFound) { ... }         // 判断(第 4 章)
while (!hasError) { ... }    // 循环条件(第 5 章)

命名习惯:布尔变量常起成 is / has / can 开头——isValid、hasError、canRetry。读起来像一句话,条件判断就自带说明。

三、与整数之间的转换规则

从 到 规则
int → bool 非 0 就是 true,0 就是 false
bool → int true 变 1,false 变 0
bool 参与运算 按 1 和 0 参与
bool t = 5;          // 5 非 0 → true
bool f = 0;          // 0 → false
int n = true;        // n = 1

cout << (true + true) << endl;   // 2  (按 1+1 算)

这条"非 0 即真"很重要:它就是为什么 if (n) 能当 if (n != 0) 用(第 4 章会大量出现)。

四、两个必须知道的输出/输入细节

细节一:cout 默认把 bool 按数字打印

cout << true << endl;                  // 输出 1
cout << false << endl;                 // 输出 0
cout << boolalpha << true << endl;     // 输出 true(加上 boolalpha 才是文字)
cout << noboolalpha << true << endl;   // 关掉,回到 1

新人常愣住的地方:cout << (5 > 3); 输出 1 而不是 true——不是错的,是默认按整数打印。

细节二:cin >> bool 只认 0 和 1

bool b;
cin >> b;            // 输入 0 → false;输入 1 → true
                     // 输入 2 或 "abc" → 输入失败,b 变成 false(还可能卡住后续输入)

结论:别用 cin 直接读布尔。要读"是/否",先读成 int 或字符,再自己判断:

int ans;
cin >> ans;
bool yes = (ans == 1);

五、动手 Demo:把转换规则跑一遍

新建 booltype.cpp:

#include <iostream>
using namespace std;

int main() {
    bool ok = (5 > 3);
    cout << "5 > 3 = " << ok << endl;                       // 1
    cout << "加 boolalpha:" << boolalpha << ok << endl;     // true

    bool fromInt = 5;                 // 非 0 → true
    cout << "5 转成 bool 是 " << fromInt << endl;            // true

    int fromBool = true;              // true → 1
    cout << "true 转成 int 是 " << fromBool << endl;         // 1

    cout << "true + true = " << (true + true) << endl;       // 2
    cout << "sizeof(bool) = " << sizeof(bool) << endl;       // 1
    return 0;
}

看到什么算成功:能看到 1、true、2、1 这些结果,并理解每一个都是从哪来的。

30 秒实验:把 bool fromInt = 5; 改成 bool fromInt = -3;——仍然是 true(只要不是 0 就是真)。负数也是"真",这一点在写条件判断时经常用到。

六、常见误区

  1. "cout << true 应该输出 true"——默认输出 1。想看到文字要加 boolalpha
  2. "bool 只占 1 位"——占 1 字节。它"看起来"只需要 1 位,但 C++ 没法单独存取一个位
  3. "写 if (isOk == true) 更清楚"——多余。直接写 if (isOk) 就行;== true 反而多一次可能的写错机会(把 == 写成 =)
  4. "cin >> bool 可以读 yes/no"——不行,只认 0 和 1。要灵活的输入就自己解析(先读字符串再判断)
自测四问(点开对答案) 1. `bool` 有几个值?占几字节?——**两个**(`true` / `false`);占 **1 字节**。 2. 整数怎么变成 `bool`?——**非 0 为 `true`,0 为 `false`**。 3. `cout << true` 输出什么?想输出 `true` 怎么办?——输出 **1**;加 `boolalpha`:`cout << boolalpha << true;`。 4. `cin >> bool` 有什么坑?——**只接受 0 和 1**,其他输入会失败。建议先读成 `int` 再自行判断。

相关笔记