如何在包含 typedef 时用从右到左的规则解释变量声明

How to interpret variable declarations with right to left rule while typedef is included?

本文关键字:规则 解释 变量 声明 从右到左 包含 typedef      更新时间:2023-10-16

涉及typedef时,使用从右到左的规则来解释变量声明时遇到问题。

在C++入门第 5 版书中,我看到了以下代码:

typedef char *pstring;
const pstring cstr = 0; // cstr is a constant pointer to char
const pstring *ps; // ps is a pointer to a constant pointer to char

如果我用 char * 替换字符串,那么它就是这样:

const char *cstr

所以我希望 cstr 是指向常量字符的指针。但书中的注释指出指针本身是恒定的。我的问题是我的思维方式出了什么问题。

> typedef不是宏。您不只是用文本替换它。

将其读作cstr是一个"常量pstring",这是一个"常量(指向字符的指针("。将其与const char*进行比较,后者是"指向常量char的指针"。

如果要替换 typedef,它将如下所示:

char* const cstr = 0;
char* const* ps;

可以在这里阅读:

如果使用 const 类型限定符(通过 使用typedef(,数组类型不是常量限定的,但其 元素类型为

因为 pstring 是 typedef 到 char *,所以const pstring cstrchar * const cstr,而不是const char * cstr