const
是 C++ 中用于定义常量或指定不可变性的关键字,它在不同上下文中有不同的含义和用法。下面是对 const
的全面解析:
1. 基本用法
定义常量
const int MAX_SIZE = 100;
const double PI = 3.14159;
这些值在程序运行期间不能被修改
必须在定义时初始化
与指针结合
const int* ptr1; // 指向常量的指针(指针可变,指向的内容不可变)
int* const ptr2; // 常量指针(指针不可变,指向的内容可变)
const int* const ptr3; // 指向常量的常量指针(都不可变)
2. 函数中的 const
函数参数
void print(const std::string& str) {// str 不能被修改std::cout << str;
}
防止函数内部意外修改参数
对于大型对象,const 引用可避免拷贝
函数返回值
const int* getPointer() {static int value = 42;return &value;
}
返回的指针不能用于修改指向的值
3. 类中的 const
const 成员函数
class MyClass {
public:int getValue() const {// 不能修改类的成员变量return value;}
private:int value;
};
承诺不修改对象状态
可以被 const 对象调用
const 数据成员
class Circle {
public:Circle(double r) : radius(r) {}
private:const double radius; // 必须在构造函数初始化列表中初始化
};
4. constexpr (C++11 引入)
constexpr int square(int x) {return x * x;
}constexpr int val = square(5); // 编译时计算
表示值或函数可以在编译时计算
比 const 更严格,所有 constexpr 都是 const
5. mutable 关键字
class Cache {
public:int getValue() const {if (!valid) {// 即使是在 const 成员函数中,也可以修改 mutable 成员cachedValue = expensiveCalculation();valid = true;}return cachedValue;}
private:mutable int cachedValue;mutable bool valid = false;
};
允许在 const 成员函数中修改特定成员
最佳实践
默认使用 const 除非需要修改
对于函数参数,优先使用 const 引用传递大型对象
对于不修改对象状态的成员函数声明为 const
使用 constexpr 替代宏定义常量
const 的正确使用可以提高代码的安全性和可读性,是 C++ 编程中的重要概念。