gpt4 book ai didi

c++ - C++中指针数组中的const限定符

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:49 25 4
gpt4 key购买 nike

假设我有一个指向整数的指针数组(即每个元素都是一个指向 int 的指针)

int** ptrArray;

并且我想防止对数组条目指向的整数进行更改

我需要把常量放在哪里?

1. const int ** ptrArray
2. int const ** ptrArray
3. int *const* ptrArray
4. int ** const ptrArray

这有什么规定吗?比如“第一个 const 保护数据”,“第二个 const 保护指针”等等?

const 的位置背后是否有任何逻辑?放在哪里和它保护什么之间有什么联系?

这对我来说是一个非常令人困惑的问题,如果有人可以给我任何指导或链接,我可以在哪里阅读更多关于如何以及在何处使用 const 的内容,我会根据我想要保护的内容(以防我需要在 3 维数组中使用 const 左右)

最佳答案

are there any rules for this? like "first const protects data", "second const protects the pointer" and so on?

是的:const 应用于左侧,除非那里什么都没有,否则它应用于右侧。

因此,这:

int const** ptrArray;

但是,作为一个特例,这是等价的:

const int** ptrArray;

这意味着通用模式 const int x; 实际上是 int const x; 的伪装。

关于c++ - C++中指针数组中的const限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33070377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com