const int &x和int const &x有何区别?谢谢~

来源:百度知道 编辑:UC知道 时间:2024/06/04 19:59:59
请详细解释区分,谢谢~

寒...

不过先声明我以下的内容是针对C++而言...

对于除指针以外的其他常量声明句法来说,
const type name

type const name
的效果是相同的, 即都声明一个类型为type名为name的常量,如:

const int x = 1;

int const x = 1;

还有

int x = 1;
const int &y = x;

int const &y = x;
都是等效的, 只是写法的风格不同而已, 有人喜欢用const type name, 比如STL的代码; 另外一些人喜欢写成type const name, 比如boost中的大量代码, 其实效果都是一样的。

对于指针来说, const出现在*号的左边还是右边或是左右都有才有区别, 具体的:

const type *p; // 一个不能修改其指向对象的type型指针
// 其实和type const *p等效

type * const p; // 一个不能修改其自身指向位置的type型指针

const type * const p;
// 一个既不能修改其指向对象也不能修改其自身指向位置的type型指针
// 也和type const * const p等效

而C++中的引用当引用了一个值后,就不能把其修改为引用另外一个值,这相当于type * const p的指针, 如:

int a, b;
int &c = a; // 声明时就和a绑定在一起
c = b; // 是把b的值赋给a, 而不是把b作为c的另一个引用

所以引用的功能其实和type * const p指针是相同的, 即其引用(指向)的位置不可改变, 如果声明引用时再加上const, 其实就相当于const type * const p型的指针了, 所以声明引用时,const type