Thinking C++ 第2章 - 基础语法与类型

来源信息

  • original_path: /田浩然上传的资料/1A004_C++程序设计/参考资料/Thinking C++ 中文版/02.pdf
  • file_size: 687.05 KB
  • pages: 21
  • processed_date: 2026-09-29
  • method: PDF文本提取
  • status: done

核心内容概述

《Thinking in C++》第2章,介绍C++基础语法、数据类型、变量声明和基本输入输出。


一、C++程序结构

1.1 最小C++程序

#include <iostream>
using namespace std;
 
int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

1.2 预处理器指令

  • #include:包含头文件
  • #define:宏定义

二、数据类型

2.1 基本类型

  • int:整数
  • float:单精度浮点
  • double:双精度浮点
  • char:字符
  • bool:布尔

2.2 类型修饰符

  • short、long:调整大小
  • signed、unsigned:有符号/无符号

2.3 类型大小(典型值)

类型大小范围
char1字节-128 to 127
int4字节±2×10^9
float4字节7位有效数字
double8字节15位有效数字

三、变量声明

3.1 声明语法

int x;           // 声明整数变量
float price = 19.99;  // 声明并初始化
double pi = 3.14159;
char grade = 'A';
bool flag = true;

3.2 命名规则

  • 只能包含字母、数字、下划线
  • 不能以数字开头
  • 区分大小写
  • 不能使用关键字

四、输入输出

4.1 输出(cout)

cout << "Value: " << x << endl;

4.2 输入(cin)

int x;
cin >> x;

4.3 格式化输出

cout << fixed << setprecision(2) << price;  // 保留两位小数

五、运算符

5.1 算术运算符

  • +、-、*、/、%

5.2 关系运算符

  • ==、!=、<、>、<=、>=

5.3 逻辑运算符

  • &&(与)、||(或)、!(非)

5.4 赋值运算符

  • =、+=、-=、*=、/=、%=

六、控制流

6.1 条件语句

if (condition) {
    // ...
} else if (another) {
    // ...
} else {
    // ...
}

6.2 循环语句

// for循环
for (int i = 0; i < 10; i++) {
    // ...
}
 
// while循环
while (condition) {
    // ...
}
 
// do-while循环
do {
    // ...
} while (condition);

6.3 switch语句

switch (value) {
    case 1:
        // ...
        break;
    case 2:
        // ...
        break;
    default:
        // ...
}

七、数组与字符串

7.1 数组声明

int numbers[10];
char name[20];

7.2 字符串处理

#include <string>
string s = "Hello";
s += " World";

关键概念总结

  1. 数据类型:基本类型、类型修饰符、类型大小
  2. 变量声明:命名规则、初始化
  3. 输入输出:cin/cout、格式化
  4. 运算符:算术、关系、逻辑、赋值
  5. 控制流:if、switch、for、while、do-while
  6. 数组字符串:基本操作

与其他知识关联