作用:用于声明常量变量,限制某些数据的可修改性。
常量变量
使用 const
声明的变量在初始化后不能被修改。这有助于防止意外地改变某些重要的值。
常量指针和指向常量的指针
指针可以使用 const
,这样可以控制指针本身或指向的数据的可修改性。
- 常量指针(指向常量数据):指针指向的内容不可修改。
- 指向常量的指针:指针本身是常量,不可修改指向的地址。
#include <iostream>
void func(const int* ptr) {
// *ptr = 5; // 这将导致编译错误,不能修改指向的值
}
int main() {
int value = 10;
const int* pValue = &value;
func(pValue); // 传入指向常量的指针
return 0;
}
void func(int* const ptr) {
// ptr = nullptr; // 这将导致编译错误,不能修改指针的地址
*ptr = 20; // 但可以修改指针指向的值
}
常量成员函数
在类中,const
可以用于成员函数,表明该函数不会修改类的成员变量。适用于访问器方法(getter)。
#include <iostream>
class MyClass {
private:
int value;
public:
MyClass(int v) : value(v) {}
// 常量成员函数
int getValue() const {
return value;
}
};
int main() {
MyClass obj(10);
std::cout << "Value: " << obj.getValue() << std::endl;
return 0;
}
常量数组
使用 const
声明数组,使其内容不可更改。这对于保护数组内容非常有用。