c++ - 这个typedef是必需的吗?

标签 c++ reference constants

有没有一种方法可以在不使用 typedef 的情况下完成此代码块在 C++ 中的作用?

typedef int* pointer;
int a = 3;
int* ap = &a;
const pointer& apr = ap;
*apr = 4;

这不行:

int b = 3;
int* bp = &b; 
const int*& bpr = bp; 
*bpr = 4;

事实上,第二个 block 不会编译,因为 const 使 bpr 成为对只读指针的引用,而不是对读写指针的 const 引用。我有点希望括号能救我:

const (int*)& bpr = bp; 

...但运气不好。那么我必须对指针类型进行类型定义,以便创建对读写指针的常量引用吗?

最佳答案

使用 spiral rule :

int* const &bpr = bp; 

这被读作 bpr 是对指向 int 的常量指针的引用

有关示例,请参阅 here .

感谢 dasblinkenlight 指出原始答案中的括号不是必需的。

关于c++ - 这个typedef是必需的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20308925/

相关文章:

共享库的 C++ 头文件,要安装哪些头文件? (最佳实践)

c++ - 现代 C++ 中的默认构造函数

perl - 如何访问 XML::Simple 返回的数据结构中的值?

C# - 此声明的字符串是否被视为常量?

c - 通过 const 指针传递与通过内置类型的值传递。效率

c++ - 什么时候需要 const volatile 对象?

c++ - 为什么一旦我将引用声明为 const,它就可以接受不同类型的数据?

c++ - const 参数 vs const 引用参数

c++ - 使用 placement new 来更改 reference_wrapper 持有的变量类型是否定义了行为?

C++:命名空间中变量的生命周期