行业知识
const 关键字的作用
2026-11-13 07:36:09
来源:互联网转载
const 关键字的作用
- 定义变量
- 修饰函数参数
- 修饰函数返回值
- 类中常成员函数
定义变量
- 声明变量不可修改
- 相较于宏index.php/tags-653.html" >可以进行类型检查
const int MAX_LENGTH = 100;int x = 10, y = 10, z = 10;// ptr是一个指向const int的指针const int* ptr = &x;// ptr1是一个指向int的const指针int* const ptr1= &y;// ptr2是一个指向const int的const指针const int* const ptr2 = &z;/*** ptr指向的值不可变,但指针本身可变。* ptr1指向的值可变,但指针本身不可变。* ptr2指向的值和指针本身都不可变。*/
注意:
- 将 const 定义的 常量变量 名称设为全大写
- 声明一个 const 变量时,必须立即对其进行初始化
- const 和指针结合时,先左结合再右结合进行判断
修饰函数参数
- 仅仅表示参数在函数内部不会被修改
- 修饰函数参数、修饰函数返回值都不可区分函数重载
void add(const int& a, const int& b) { return a + b;}// error: call of overloaded ‘add(int, int)’ is ambiguous// b.cpp:4:5: note: candidate: ‘int add(const int&, const int&)’// b.cpp:8:11: note: candidate: ‘const int add(int, int)’int add(const int& a, const int& b) { return a + b;}const int add(int a, int b) { return a + b;}int main() { int x = add(1, 2); cout 5 public: 6 const int constValue = 10; 7 8 int mutableValue = 20; 9 void showValuesConst() const { 10 cout 19 cout 24 cout 28 cout 34 Example ex; 35 ex.showValuesConst(); 36 ex.modifyShow(); 37 const Example ex1; 38 ex1.showValuesConst(); 39 return 0; 40 }
上一篇:怎么看接收邮箱服务器?
下一篇:淘宝网的服务器在哪里?