Rob*_*obz 2 c++ const reference
有没有办法在不使用typedef的情况下完成这个代码块在C++中的作用?
typedef int* pointer;
int a = 3;
int* ap = &a;
const pointer& apr = ap;
*apr = 4;
Run Code Online (Sandbox Code Playgroud)
这不会这样做:
int b = 3;
int* bp = &b;
const int*& bpr = bp;
*bpr = 4;
Run Code Online (Sandbox Code Playgroud)
实际上,第二个块不会编译,因为它const使bpr成为对只读指针的引用,而不是对读写指针的const引用.我有点希望括号能救我:
const (int*)& bpr = bp;
Run Code Online (Sandbox Code Playgroud)
......但那里没有运气.所以我必须键入dede指针类型,以便创建一个对读写指针的const引用?
chr*_*ris 11
使用螺旋规则:
int* const &bpr = bp;
Run Code Online (Sandbox Code Playgroud)
这是读取的,因为bpr是对int的常量指针的引用.
有关示例,请参见此处.
感谢dasblinkenlight指出原始答案中的括号不是必需的.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |