为常量指针创建别名
Creating an alias for a constant pointer
我想知道为什么最后一个语句无效?我对错误的信息有点困惑,如果有人能澄清错误,我将不胜感激。我知道下面的代码什么也不做。我只是在尝试改进我的观念。我想为指针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
定义为指向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
你的评论给出了答案。在代码中,您定义了一个指向指针的常量引用,这是没有意义的。您需要一个指向const的指针的引用,这是我的第二行。
相关文章:
- 如何在C++20中创建模板别名的推导指南
- 为类的成员创建别名
- 是否可以为 std::cout 创建别名?
- C++使用模板为基元类型创建别名?
- 为 OpenMP 函数创建别名 ||部分禁用 openMP
- Cython 创建 C 函数别名
- 如何在C 中为多个类创建一个别名
- 根据模板参数条件 C++17 创建成员别名
- 如何为 cpp 和 h 文件创建别名(并忽略编译器__attributes__)
- 创建为功能的别名
- 如何使用类模板专用化创建别名模板的专用化
- 创建一个从一种类型到另一种类型的别名
- 通过引用创建别名以提升:shared_ptr
- 为变量创建局部别名会增加开销吗?
- 是否可以创建模板别名
- 创建函数别名
- 使用"using"创建多个别名
- 如何为 noexcept 函数指针创建别名
- 如何在Visual Studio 2013中为函数类型创建类型别名
- 创建别名时静态断言模板参数检查