为常量指针创建别名

Creating an alias for a constant pointer

本文关键字:别名 创建 指针 常量      更新时间:2023-10-16

我想知道为什么最后一个语句无效?我对错误的信息有点困惑,如果有人能澄清错误,我将不胜感激。我知道下面的代码什么也不做。我只是在尝试改进我的观念。我想为指针p

创建别名
int a =12;
int * const p = &a; //p is a constant pointer to an int - This means it can change the contents of an int but the address pointed by p will remain constant and cannot change.
int *& const m = p; //m is a constant reference to a pointer of int type <---ERROR

这些是我得到的错误

main.cpp:17:18: error: 'const' qualifiers cannot be applied to 'int*&'
     int *& const m = p; 
                  ^
main.cpp:17:22: error: binding 'int* const' to reference of type 'int*&' discards qualifiers
     int *& const m = p; 

谁能解释一下这两个错误是什么意思,特别是最后一个,如果有可能为指针p创建别名

'const' qualifiers cannot be applied to 'int*&'

引用初始化后不能重新绑定。因此,没有理由在引用上放置const限定符(不要与对const的引用混淆,后者是完全正常的),因为无论如何都无法更改。这就是第一个错误的原因。

对于第二个错误,

binding 'int* const' to reference of type 'int*&' discards qualifiers

p是一个const指针,但是您试图将对非const的引用绑定到它。这将允许您通过引用更改const指针,这是不允许的。

下面是引用p的正确方法:
int * const& m = p;

使用

int a =12;
int* const p = &a;
int* const& m = p;

这将m定义为指向intconst指针的引用

考虑以下两行:

int *const & const m = p; //m is a constant reference to a pointer of int type <---ERROR
int *const &  m = p; //m is a  reference to a pointer to a const int type <--- OK

你的评论给出了答案。在代码中,您定义了一个指向指针的常量引用,这是没有意义的。您需要一个指向const的指针的引用,这是我的第二行。