是什么const int的* const int的* const的,和INT常量*之间的区别? [英] What is the difference between const int*, const int * const, and int const *?

查看:135
本文介绍了是什么const int的* const int的* const的,和INT常量*之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是搞砸了如何使用 const int的* const int的*常量 INT常量* 正确。有没有定义,你可以和不能做什么的一套规则?

I always mess up how to use const int*, const int * const, and int const * correctly. Is there a set of rules defining what you can and cannot do?

我想知道所有的做的和不该做的所有任务中的角度,传递到功能等。

I want to know all the do's and all don'ts in terms of assignments, passing to the functions, etc.

推荐答案

阅读它向后(由顺时针/驱动螺旋规则)...

Read it backwards (as driven by Clockwise/Spiral Rule)...


  • 为int * - 指针为int

  • INT常量* - 指向const int的

  • 为int * const的 - 常量指针为int

  • INT常量* const的 - 常量指针const int的

  • int* - pointer to int
  • int const * - pointer to const int
  • int * const - const pointer to int
  • int const * const - const pointer to const int

现在第一常量可以在类型,这样的任一侧:

Now the first const can be on either side of the type so:


  • const int的* == INT常量*

  • const int的* const的 == INT常量* const的

  • const int * == int const *
  • const int * const == int const * const

如果你想要去真的疯了,你可以做这样的事情:

If you want to go really crazy you can do things like this:


  • INT ** - 指针指向int的指针

  • INT **常量 - 一个const指针的指针为int

  • 为int * const的* - 指向一个常量指针为int

  • INT常量** - 一个指针指向一个const int的

  • 为int * const的* const的 - 一个const指向const指向int

  • ...

  • int ** - pointer to pointer to int
  • int ** const - a const pointer to a pointer to an int
  • int * const * - a pointer to a const pointer to an int
  • int const ** - a pointer to a pointer to a const int
  • int * const * const - a const pointer to a const pointer to an int
  • ...

和确保我们对常量的意义

And to make sure we are clear on the meaning of const

const int* foo;
int *const bar; //note, you actually need to set the pointer 
                //here because you can't change it later ;)

是一个变量指向一个恒定的INT。这可以让你改变你点,你指出来,但不是值。通常的做法就是见过cstrings,你有一个指针为const char 。你可以改变你指向一个字符串,但你不能改变这些字符串的内容。这是重要的,当字符串本身是在一个节目的数据段和不应该改变。

foo is a variable pointer to a constant int. This lets you change what you point to but not the value that you point to. Most often this is seen with cstrings where you have a pointer to a const char. You may change which string you point to but you can't change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn't be changed.

是一个常量或固定指针,可以改变一个值。这就好比没有额外的语法糖的参考。由于这一事实,通常你会使用一个参考的地方,除非你需要允许空指针,你会使用 T * const的指针。

bar is a const or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a T* const pointer unless you need to allow null pointers.

这篇关于是什么const int的* const int的* const的,和INT常量*之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆