这个typedef是必需的吗

Is this typedef required?

本文关键字:typedef 这个      更新时间:2023-10-16

有没有一种方法可以在不使用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;

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

const (int*)& bpr = bp; 

但没有运气。那么,我是否有来typedef指针类型,以便创建对读写指针的常量引用?

使用螺旋规则:

int* const &bpr = bp; 

这被读取为bpr是指向int的常量指针的引用。

有关示例,请参见此处。

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