我总是搞乱如何使用const int*
, const int * const
, and int const *
正确。是否有一套规则来定义你可以做什么和不能做什么?
我想知道在分配、传递给函数等方面所有该做和不该做的事情。
向后阅读(由顺时针/螺旋规则):
-
int*
- 指向 int 的指针
-
int const *
- 指向 const int 的指针
-
int * const
- 指向 int 的 const 指针
-
int const * const
- 指向 const int 的 const 指针
现在第一个const
可以位于类型的任一侧,因此:
-
const int *
== int const *
-
const int * const
== int const * const
如果你想变得真正疯狂,你可以这样做:
-
int **
- 指向 int 指针的指针
-
int ** const
- 指向 int 指针的 const 指针
-
int * const *
- 指向 const 指针的指针,该指针指向 int
-
int const **
- 指向 const int 的指针
-
int * const * const
- 指向 int 的 const 指针的 const 指针
- ...
如果您不确定,可以使用类似的工具cdecl+自动将声明转换为散文。
为了确保我们清楚的含义const
:
int a = 5, b = 10, c = 15;
const int* foo; // pointer to constant int.
foo = &a; // assignment to where foo points to.
/* dummy statement*/
*foo = 6; // the value of a can´t get changed through the pointer.
foo = &b; // the pointer foo can be changed.
int *const bar = &c; // constant pointer to int
// note, you actually need to set the pointer
// here because you can't change it later ;)
*bar = 16; // the value of c can be changed through the pointer.
/* dummy statement*/
bar = &a; // not possible because bar is a constant pointer.
foo
是一个指向常量整数的变量指针。这使您可以更改所指向的内容,但不能更改所指向的值。最常见的是 C 风格的字符串,其中有一个指向const char
。您可以更改指向的字符串,但无法更改这些字符串的内容。当字符串本身位于程序的数据段中且不应更改时,这一点很重要。
bar
是指向可以更改的值的常量或固定指针。这就像没有额外语法糖的参考。因此,通常您会在使用引用的地方使用引用T* const
指针,除非你需要允许NULL
指针。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)