c++ - c ++中常量指针的目的是什么?
问题描述
我是 C++ 的初学者,并且有以下关于指针的用途的问题,其中地址和它指向的值都不能更改(constEverything
在示例中)。
例子:
int main()
{
int i = 1;
int j = 2;
int* const constPoint = &i;
*constPoint = 3; // legal
constPoint = &j; // illegal
const int* constVal = &i;
*constVal = 3; // illegal
constVal = &j; // legal
const int* const constEverything = &i;
*constEverything = 3; // illegal
constEverything = &j; // illegal
}
在示例中,有不同类型的指针。constVal
您可以更改地址,也constPoint
可以更改基础价值。因为constEverything
你什么都做不了。
对我来说,这样一个指针的目的是通过常量引用传递事物。为什么我不应该只使用const type &val来代替?对我来说,一个 const 引用似乎要容易得多,它使const type* const val过时了。
解决方案
常量指针之所以有用,主要有两个原因。
this
是成员函数const
中的指针。const
const
指针也可以设置为nullptr
。
我的第一点有点循环,this
可能是引用类型或const
引用类型,但引用在 C++ 标准中出现较晚,任何更改都会中断。
推荐阅读
- spring-boot - Http 400 使用 resttemplate postforobject
- python - 在已排序的二维数组中搜索数字
- c++ - 为什么我们需要不同的阴影贴图视口
- amazon-web-services - 为从 s3 下载的文件添加一个变量作为文件名
- angular - angularfire5 & firebase autocomplete 相当于 WHERE LIKE?
- ios - Cordova 地理定位插件无法显示位置消息
- vb.net - 如何反序列化在 API 调用中收到的具有多个标签的大型 JSON
- linux - Bash - 基于已解析 CSV 的变量 case 语句选项?
- c++ - 访问属性表中的控件
- javascript - 如何在输入字段上使用退格键删除字符