gpt4 book ai didi

c++ - const int*、const int * const 和 int const * 之间有什么区别?

转载 作者:行者123 更新时间:2023-12-02 01:38:18 28 4
gpt4 key购买 nike

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

我想知道在赋值、传递给函数等方面所有该做和不该做的事情。

最佳答案

向后阅读(由 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 * - 指向 int 的 const 指针
  • 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 指针。

关于c++ - const int*、const int * const 和 int const * 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55122649/

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