我想知道为什么最后一句话无效?我对错误的信息有点困惑,如果有人能澄清错误,我会很感激.我知道以下代码什么都不做.我只是试图改进我的概念.我想为指针创建一个别名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
Run Code Online (Sandbox Code Playgroud)
这些是我得到的错误
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;
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释这两个错误特别是最后一个错误,以及是否可以为指针p创建一个别名.
'const' qualifiers cannot be applied to 'int*&'
Run Code Online (Sandbox Code Playgroud)
初始化后,引用无法重新绑定.所以没有理由在引用上放置const限定符(不要与const-to-const混淆,这是完全正常的),因为它无论如何都无法改变.这就是第一个错误的原因.
对于第二个错误,
binding 'int* const' to reference of type 'int*&' discards qualifiers
Run Code Online (Sandbox Code Playgroud)
p是一个const指针,但您正在尝试将引用绑定到非const.这将允许您通过引用更改const指针,这是不允许的.
以下是引用以下内容的正确方法p:
int * const& m = p;
Run Code Online (Sandbox Code Playgroud)