doc/docs/CPlusPlus-main/04_C++的常量.md
sairate fa9377e4ae docs(book): 添加现代 C++教程及相关代码
- 新增现代 C++ 教程的 Preface 章节,包括英文和中文版本
- 添加 C++ Primer 练习代码
- 新增 Learn C++ 教程的 C++ 开发简介章节
- 添加头文件解析文档
- 更新 mkdocs.yml,包含新教程的目录结构
- 修改项目设置,使用 Python 3.10环境
2025-07-08 09:52:45 +08:00

75 lines
1.4 KiB
Markdown
Raw Permalink 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.

# C++的常量
# 1. 常量
① 常量,用于记录程序中不可更改的数据。
② C++定义常量两种方式,如下所示:
1. #define 宏常量:#define 常量名 常量值
- note通常在文件上方定义表示一个常量。
2. const修饰的变量 const 数据类型 常量名 = 常量值
- note通常在变量定义前加关键字const修饰该变量为常量不可修改。
## 1.1 #define 常量名 常量值
```python
#include <iostream>
using namespace std;
#define Day 7
int main()
{
/*
Day = 14; //错误Day是常量一旦修改就会报错
cout << "一周总共有:" << Day << "天" << endl;
*/
cout << "一周总共有:" << Day << "天" << endl;
// 输出语句cout << "提示语" << 变量 << endl;
system("pause");
return 0;
}
```
运行结果:
- 一周总共有7天
- 请按任意键继续. . .
## 1.2 const 数据类型 常量名 = 常量值
```python
#include <iostream>
using namespace std;
int main()
{
/*
const int month = 12;
month = 24; //错误const修饰的变量也称为常量
*/
int month = 12;
month = 24; //正确这样可以修改变量的值
cout << "一年总共有:" << month << "个月" << endl;
system("pause");
return 0;
}
```
运行结果:
- 一年总共有24个月
- 请按任意键继续. . .