doc/notebook/docs/NOI竞赛大纲/二.C++程序设计/1.程序基本概念.md

131 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 程序基本概念
## 一、标识符、关键字、常量、变量、字符串、表达式的概念
### 1. 标识符Identifier
- 标识符是程序中用于标识变量、函数、数组、类等用户自定义元素的名称。
- 命名规则:只能由字母、数字和下划线组成,不能以数字开头,不能使用关键字。
```cpp
int score;
float total_score;
```
### 2. 关键字Keyword
- 关键字是编程语言保留的、具有特定含义的标识符,不能作为变量名或函数名使用。
- 示例C++
```text
int, if, while, return, class, public, private
```
### 3. 常量Constant
- 程序中固定不变的数据值。
- 类型包括整型常量10、浮点常量3.14)、字符常量('a')、字符串常量("hello")。
```cpp
const double PI = 3.14;
```
### 4. 变量Variable
- 变量是程序运行过程中值可以改变的量,需先定义后使用。
- 每个变量都有一个名字、数据类型和存储空间。
```cpp
int age = 18;
```
### 5. 字符串String
- 一系列字符组成的序列,通常用双引号括起来,如 "Hello, world!"。
- 在C++中使用 `std::string` 类型:
```cpp
#include <string>
std::string name = "Alice";
```
### 6. 表达式Expression
- 表达式是由变量、常量、运算符、函数调用等组成的语法结构,能产生一个值。
- 示例:
```cpp
a + b * c
x > 0 && y < 10
```
---
## 二、常量与变量的命名、定义及作用
### 1. 命名规则
- 变量和常量命名应具有可读性,建议采用有意义的名称。
- 遵守语言的语法规则:字母、数字和下划线组成,不能以数字开头,不能使用关键字。
![命名示意图](https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Variable_naming.svg/800px-Variable_naming.svg.png)
### 2. 定义方式
- 常量定义:
```cpp
const int MAX = 100;
```
- 变量定义:
```cpp
int age = 18;
float pi = 3.14;
```
### 3. 作用
- 常量用于保存不会变化的值,增加程序可读性和安全性。
- 变量用于存储和操作程序运行过程中的数据。
---
## 三、头文件与名字空间的概念
### 1. 头文件Header File
- 头文件是包含函数声明、宏定义、类定义等内容的文件,通常以 `.h``.hpp` 结尾。
- 示例:`#include <iostream>` 引入输入输出库。
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, world!" << endl;
return 0;
}
```
### 2. 名字空间Namespace
- 名字空间用于避免不同模块中标识符的命名冲突。
- 示例:
```cpp
using namespace std; // 使用标准命名空间
std::cout << "Hello"; // 不使用 using 时需加 std:: 前缀
```
---
## 四、编辑、编译、解释、调试的概念
### 1. 编辑Editing
- 使用文本编辑器编写或修改源代码。
### 2. 编译Compiling
- 将源代码(如 `.cpp` 文件)翻译为目标代码(机器语言),形成可执行文件。
![编译过程示意图](https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Compiler_structure.svg/800px-Compiler_structure.svg.png)
### 3. 解释Interpreting
- 一边读取源代码一边执行,不生成可执行文件(如 Python、JavaScript 解释执行)。
### 4. 调试Debugging
- 在程序开发过程中发现并修正错误的过程。
- 常用方法:断点调试、单步执行、查看变量值等。