如何在包含 typedef 的情况下使用从右到左的规则解释变量声明?
How to interpret variable declarations with right to left rule while typedef is included?
我在使用从右到左的规则解释涉及 typedef 的变量声明时遇到了问题。
在 C++ primer 第 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 * 替换 pstring,那么它会像这样:
const char *cstr
所以我希望 cstr 是一个指向 const char 的指针。但是书中的评论指出指针本身是不变的。我的问题是我的思维方式有什么问题。
A typedef
不是宏。你不只是文本替换它。
读作 cstr
是一个 "constant pstring
",这是一个 "constant (pointer to char)"。将此与 const char*
进行比较,即 "pointer to constant char
"。
如果您要替换 typedef,它将如下所示:
char* const cstr = 0;
char* const* ps;
可读here:
If an array type is declared with the const type qualifier (through
the use of typedef), the array type is not const-qualified, but its
element type is
因为 pstring 是 char *
的类型定义,const pstring cstr
是 char * const cstr
,而不是 const char * cstr
。
我在使用从右到左的规则解释涉及 typedef 的变量声明时遇到了问题。
在 C++ primer 第 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 * 替换 pstring,那么它会像这样:
const char *cstr
所以我希望 cstr 是一个指向 const char 的指针。但是书中的评论指出指针本身是不变的。我的问题是我的思维方式有什么问题。
A typedef
不是宏。你不只是文本替换它。
读作 cstr
是一个 "constant pstring
",这是一个 "constant (pointer to char)"。将此与 const char*
进行比较,即 "pointer to constant char
"。
如果您要替换 typedef,它将如下所示:
char* const cstr = 0;
char* const* ps;
可读here:
If an array type is declared with the const type qualifier (through the use of typedef), the array type is not const-qualified, but its element type is
因为 pstring 是 char *
的类型定义,const pstring cstr
是 char * const cstr
,而不是 const char * cstr
。