c++指针数组中的Const限定符
const qualifier in c++ in array of pointers
假设我有一个指向整型的指针数组(即每个元素都是指向整型的指针)
int** ptrArray;
和我想要防止改变数组
的项所指向的整数我需要把const放在哪里?
1. const int ** ptrArray
2. int const ** ptrArray
3. int *const* ptrArray
4. int ** const ptrArray
这有什么规则吗?就像"第一个const保护数据","第二个const保护指针"等等?
const的位置背后有什么逻辑吗?把它放在哪里和它所保护的东西之间有联系吗?
这对我来说是一个非常令人困惑的问题,如果有人能给我任何指导或链接,我可以根据我想要保护的内容(万一我需要在三维数组中使用const)阅读更多关于如何以及在哪里使用const的信息,我将非常感激
这有什么规则吗?就像"第一个const保护数据","第二个const保护指针"等等?
是: const
适用于左侧,除非那里没有任何内容,否则它适用于右侧
:
int const** ptrArray;
但是,作为特殊情况,这是等价的:
const int** ptrArray;
这意味着常见的模式const int x;
实际上是 int const x;
的伪装。
从变量开始读取修饰符
。
3. int *const* ptrArray
-
ptrArray
为变量。 -
*ptrArray
表示指向某物的指针 -
const* ptrArray
表示指向常量的指针 -
*const* ptrArray
表示指向某物的常量指针
所以int *const* ptrArray;
声明了一个指向(非常量)int
的常量指针
要理解所有示例,您需要知道的最后一个技术细节是,int const
和const int
是表示同一类型的两种不同方式。
http://cdecl.org报告(或多或少,一个是无效的语法错误):
const int ** ptrArray: declare ptrArray as pointer to pointer to const int
int const ** ptrArray: declare ptrArray as pointer to pointer to const int
int * const * ptrArray: declare ptrArray as pointer to const pointer to int
int ** const ptrArray: declare ptrArray as const pointer to pointer to int
所以你要找的是:
const int ** ptrArray
int const ** ptrArray
相关文章:
- 将const指针(EVP_MD)保存到变量中,以将其重新使用为类方法(HMAC)
- std :: allocator_traits ::用const指针构造
- 汇编问题试图使用qobject_cast进行const指针
- C++ 两个具有相互指向 const 指针的对象
- 我想将指向 const 对象的指针放入包含非 const 指针的容器中.我有什么选择
- 传统代码突变const指针.任何合法的原因
- C#等效于C 中的const指针
- 返回指向 const 数据成员和 'auto' 关键字的 const 指针。有点困惑
- 函数返回由const指针向量生成的指针
- 您如何使用成员正确初始化构造的结构,该构件是指向const值的const指针
- 使用 const 指针的 C 样式字符返回不正确的结果
- 有没有办法将 std::stack<pointer> 转换为 std::stack<const 指针>?
- 为什么当 typedef const 指针与额外的 const 一起使用时,编译器不会给出错误?
- 如何将const_cast的const指针向量映射到非常量指针向量
- 什么场景可能需要使用 需要 const 指针指向(非常量常量)数据
- 强制转换 const 指针以使用旧版 C 代码
- const ref 和 const 指针 c++ 之间的区别
- 将 const 传递给接受 const 指针的函数是不正确的
- 指向指针数组的Const指针
- C++Const指针声明