Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为常量指针创建别名_C++ - Fatal编程技术网

C++ 为常量指针创建别名

C++ 为常量指针创建别名,c++,C++,我想知道为什么最后一句话是无效的?我对错误信息有点困惑,如果有人能澄清错误,我将不胜感激。我知道下面的代码没有任何作用。我只是在尝试改进我的概念。我想为指针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

我想知道为什么最后一句话是无效的?我对错误信息有点困惑,如果有人能澄清错误,我将不胜感激。我知道下面的代码没有任何作用。我只是在尝试改进我的概念。我想为指针
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
请任何人解释一下这两个错误是什么意思,特别是最后一个错误,以及是否可以为指针p创建别名

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

对于第二个错误

binding 'int* const' to reference of type 'int*&' discards qualifiers
p
是常量指针,但您正试图将非常量的引用绑定到它。这将允许您通过引用更改常量指针,这是不允许的

以下是引用
p
的正确方法:

int * const& m = p;
使用


m
定义为指向
int
const
指针的引用,请考虑以下两行:

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

int*const&const m=p//m是对int类型指针的常量引用,因为它是对非常量指针的引用。如果允许,您可以通过引用修改
p
,但是
p
是常量<代码>常量int*&m=p
int a =12;
int* const p = &a;
int* const& m = p;
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