小编典典

const int*、const int * const 和 int const * 有什么区别?

c++

我总是搞砸如何正确使用const int*,const int * constint const *。是否有一套规则来定义你能做什么和不能做什么?

我想知道在分配、传递给函数等方面的所有注意事项。


阅读 267

收藏
2022-02-21

共1个答案

小编典典

向后阅读(由Clockwise/Spiral Rule驱动):

  • 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 指针

并确保我们清楚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指针。

2022-02-21