欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > C++ 中的 Const 关键字(1)

C++ 中的 Const 关键字(1)

2025/2/26 0:09:36 来源:https://blog.csdn.net/luoganttcc/article/details/145599854  浏览:    关键词:C++ 中的 Const 关键字(1)

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;|      ~~~^~~

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词