C++ 常量
外观
C++常量[编辑 | 编辑源代码]
简介[编辑 | 编辑源代码]
在C++中,常量(Constant)是指程序运行期间其值不能被改变的标识符。常量提供了一种增强代码可读性、安全性和维护性的方式,通过明确标识不应被修改的值,帮助开发者避免意外修改重要数据。
C++支持多种常量类型:
- 字面常量(Literal constants)
- 使用关键字定义的常量
const
- 使用关键字定义的编译期常量(C++11引入)
constexpr
- 枚举常量(Enumeration constants)
- 预处理器宏定义的常量(较不推荐)
const关键字[编辑 | 编辑源代码]
const
是C++中最常用的常量定义方式,可以应用于变量、函数参数和成员函数。
基本语法[编辑 | 编辑源代码]
const 数据类型 常量名 = 初始值;
示例[编辑 | 编辑源代码]
#include <iostream>
int main() {
const double PI = 3.14159; // 定义双精度浮点常量
const int MAX_USERS = 100; // 定义整型常量
// PI = 3.14; // 错误:不能修改常量
std::cout << "圆周率: " << PI << std::endl;
std::cout << "最大用户数: " << MAX_USERS << std::endl;
return 0;
}
输出:
圆周率: 3.14159 最大用户数: 100
constexpr (C++11)[编辑 | 编辑源代码]
constexpr
表示值在编译时即可确定,允许编译器进行更多优化。
示例[编辑 | 编辑源代码]
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
int main() {
constexpr int fact5 = factorial(5); // 编译时计算
static_assert(fact5 == 120, "阶乘计算错误");
return 0;
}
常量指针与指向常量的指针[编辑 | 编辑源代码]
指针与常量结合使用时需特别注意语法:
示例[编辑 | 编辑源代码]
int main() {
int value = 10;
int another = 20;
// 1. 指向常量的指针(指针可以改变,指向的数据不能改变)
const int* ptr1 = &value;
// *ptr1 = 15; // 错误
ptr1 = &another; // 允许
// 2. 指针常量(指针不能改变,指向的数据可以改变)
int* const ptr2 = &value;
*ptr2 = 15; // 允许
// ptr2 = &another; // 错误
// 3. 指向常量的指针常量
const int* const ptr3 = &value;
// *ptr3 = 15; // 错误
// ptr3 = &another; // 错误
return 0;
}
实际应用案例[编辑 | 编辑源代码]
场景:游戏开发中的物理常量[编辑 | 编辑源代码]
#include <iostream>
class PhysicsEngine {
public:
static constexpr double GRAVITY = 9.8; // 重力加速度
static constexpr double AIR_RESISTANCE = 0.1;
static double calculateFallDistance(double time) {
return 0.5 * GRAVITY * time * time;
}
};
int main() {
std::cout << "2秒后物体下落距离: "
<< PhysicsEngine::calculateFallDistance(2.0)
<< " 米" << std::endl;
return 0;
}
输出:
2秒后物体下落距离: 19.6 米
常量与宏定义的比较[编辑 | 编辑源代码]
特性 | const
|
宏定义(#define) |
---|---|---|
类型安全 | 是 | 否 |
作用域 | 有 | 无 |
调试可见 | 是 | 否 |
内存占用 | 可能有 | 无 |
编译时计算 | constexpr
|
支持 |
数学公式示例[编辑 | 编辑源代码]
在物理引擎中,自由落体距离公式为: 其中:
- = 距离
- = 重力加速度(常量)
- = 时间
最佳实践[编辑 | 编辑源代码]
1. 优先使用
const
而非
#define
2. 能在编译时确定的常量使用
constexpr
3. 对于类中的常量,使用
static const
或
static constexpr
4. 给常量赋予有意义的名称(全大写是常见约定)
5. 在函数参数中,如果不修改传入参数,使用
const
引用
常见问题[编辑 | 编辑源代码]
Q:
const
和
constexpr
有什么区别? A:
const
表示运行时不修改,
constexpr
表示编译时可确定。
Q: 为什么常量通常定义在头文件中? A: 因为常量默认有内部链接,在多文件中使用需要在每个文件中定义。
Q: 常量存储在内存的什么位置? A: 取决于定义方式:
- 局部变量通常在栈上
const
- 可能被编译器优化掉
constexpr
- 全局可能在只读数据段
const