我对C++还比较陌生,正在尝试理解一些代码:
bool ClassName::ClassMethod(const STRUCT_THING* const parameterName) {}
第二个"const"在参数中的作用是什么?它与const STRUCT_THING* parameterName
有何不同之处?
谢谢!
我对C++还比较陌生,正在尝试理解一些代码:
bool ClassName::ClassMethod(const STRUCT_THING* const parameterName) {}
第二个"const"在参数中的作用是什么?它与const STRUCT_THING* parameterName
有何不同之处?
谢谢!
这意味着它是一个指向常量的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.
从右向左阅读:
parameterNam是类型为STRUCT_THING的常量指针,恰好是const。
基本上你不能改变它,也不能改变它所指向的内容。
const
不会影响函数签名。也就是说,void foo(int const * const)
和void foo(int const *)
是同一个函数的两个声明。但它确实会影响函数定义中的编译器检查,确保函数不会尝试将指针重置为其他值。 - David Rodríguez - dribeas