C++ 中的 Const 关键字
最后更新: 2024 年 8 月 6 日
本文讨论了C++中const 关键字的各种功能。只要将const 关键字附加到任何方法 ()、变量、指针变量以及类的对象上,它就会阻止特定对象/方法 ()/变量修改其数据项的值。
常量变量:
常量变量的声明和初始化有一定的规则:
const 变量在声明时不能未初始化。
不能在程序中的任何地方为其赋值。
在声明常量变量时需要为常量变量提供明确的值。
const 变量
下面是演示上述概念的 C++ 程序:
// C++ program to demonstrate the
// the above concept
#include <iostream>
using namespace std;// Driver Code
int main()
{// const int x; CTE error// x = 9; CTE errorconst int y = 10;cout << y;return 0;
}
带有指针变量的 Const 关键字:
指针可以用 const 关键字声明。因此,有三种可能的方式将 const 关键字与指针一起使用,如下所示:
当指针变量指向一个 const 值时:
句法:
const 数据类型 * 变量名称;
// C++ program to demonstrate the
// above concept
#include <iostream>
using namespace std;// Driver Code
int main()
{int x{ 10 };char y{ 'M' };const int* i = &x;const char* j = &y;// Value of x and y can be altered,// they are not constant variablesx = 9;y = 'A';// Change of constant values because,// i and j are pointing to const-int// & const-char type value// *i = 6;// *j = 7;cout << *i << " " << *j;
}
9 A
解释:在上面的例子中,i 和 j 是两个指向内存位置 const int 类型和 char 类型的指针变量,但是存储在这些相应位置的值可以像我们上面所做的那样进行更改。
否则,将会出现以下错误:如果我们尝试修改 const 变量的值。
main.cpp: In function ‘int main()’:
main.cpp:23:9: error: assignment of read-only location ‘* i’23 | *i = 6;| ~~~^~~
main.cpp:24:9: error: assignment of read-only location ‘* j’24 | *j = 7;| ~~~^~~