【问题标题】:What exactly is this type? [duplicate]这种类型究竟是什么? [复制]
【发布时间】:2012-03-18 04:47:12
【问题描述】:

可能重复:
what is the difference between const int*, const int * const, int const *

谁能给我解释一下这种类型?

char const * const blah;

我本来希望它会写成这样的:const char *。 const 发布类型是什么意思?例如int const foo.

然后,第一句话是什么意思?

【问题讨论】:

  • 分号在哪里?变量或函数或...名称在哪里?
  • 抱歉,已修复。主要问题是我的大脑完全炸了。
  • 没有任何赋值,这种类型是无用的。声明后不能更改 const blah

标签: c++


【解决方案1】:

指向常量字符的常量指针。您无法更改它指向的地址,也无法更改其末尾的字符。

【讨论】:

  • 我很困惑为什么它不是 const int * const
  • @SirYakalot : const int fooint const foo 相同。通过类似的逻辑,const int * const fooint const * const foo 相同。
  • 我从来没有新的你可以把 c​​onst 放在前面或后面。嗯。那么 const int const * 呢?
  • @SirYakalot:这是一个错误 - 您只能指定一次 const。如果你真的想写,你可以写const int volatile
  • 您甚至可以争辩说,通常最好总是将 const 放在 类型之后,因为您从内到外读取复杂的类型,并且因为在这个特定的实例中,与指针相关的常量必须在*之后。但是,实际上没有人为此烦恼。
【解决方案2】:
char const * const ptr = "Hello";

ptr 是一个指向常量字符的常量指针。这意味着ptr 和它指向的数据都不能被修改。由于指针本身是常量类型,所以需要初始化,因为以后不能重新赋值。

char const * const laterPtr; // Wrong.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-18
    • 2020-02-26
    • 2018-10-02
    • 2012-04-30
    • 2014-11-01
    • 2017-01-12
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多