一个方法参数中为什么会出现两个const?

3

我对C++还比较陌生,正在尝试理解一些代码:

bool ClassName::ClassMethod(const STRUCT_THING* const parameterName) {}

第二个"const"在参数中的作用是什么?它与const STRUCT_THING* parameterName有何不同之处?

谢谢!

3个回答

8

这意味着它是一个指向常量的const指针。

请看以下示例:

int x = 5;                // non-const int
int* y = &x;              // non-const pointer to non-const int

int const a = 3;          // const int
int* const b = &a;        // const pointer to non-const int
int const* const c = &a;  // const pointer to const int

你可以看到两个东西有可能是可变的,一个是变量,一个是指针。这两者都可以是const

const变量的工作方式与您想象的一样:

int foo = 10;
foo += 5;     // Okay!

int const bar = 5;
bar += 3;     // Not okay! Should result in a compiler warning (at least)

const指针的工作方式相同:

int foo = 10;
int bar = 5;

int* a = &foo;
a = &bar;  // Okay!

int* const b = &foo;
b = &bar;  // Not okay! Should also result in a compiler warning.

确定“const”所指的规则是什么?例如,它只是指在“const”左侧的内容吗? - BWG
@BWG 请参考这篇帖子。基本上,您需要从右到左阅读,但有几个例外。 - Cory Kramer
@Cyber,这似乎非常不直观,因为在英语中,描述符位于目标之前。谢谢你的回答! - Benjin
需要注意的是,最后一个 const 不会影响函数签名。也就是说,void foo(int const * const)void foo(int const *) 是同一个函数的两个声明。但它确实会影响函数定义中的编译器检查,确保函数不会尝试将指针重置为其他值。 - David Rodríguez - dribeas

1

从右向左阅读:

parameterNam是类型为STRUCT_THING的常量指针,恰好是const。

基本上你不能改变它,也不能改变它所指向的内容。


明白了。所以如果我只有其中一个"const",那么指针可以指向其他内容,或者该不可变指针将指向可变的内容? - Benjin

0
你正在使用一个指向常量的const指针,这是两个不同的概念。
它们之间的区别在于一个是指向常量的const指针,实际上是指向该常量变量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接