c++ - 结构可以具有类型 `Card*` 吗? (书中的例子)

标签 c++ pointers syntax typedef

我的书说

typedef Card* Cardptr;

“将新类型名称 Cardptr 定义为类型 Card* 的同义词。”我看到 * 符号仅修改 Cardptr 并且其他同义词(如果有的话)不会被 * 符号修改。这让我很困惑。我的书使它看起来像实际结构类型是 Card*,这让我认为其他同义词将具有 Card* 类型,如

typedef Card* Cardptr, n;

其中 n 也将具有类型 Card*。如果他们像这样移动 * 符号会不会更清楚?

typedef Card *Cardptr, n;

这样,您就会知道该类型实际上是 CardCardptr 只是指向它的指针,而 n 是不是指针。这是什么原因?

最佳答案

C++ 通常不关心空格,因此编译器认为以下两个语句相同:

typedef Card* Cardptr;
typedef Card *Cardptr;

同理,三个声明

int* a;
int *a;
int * a;

无法区分。


Wouldn't it be clearer if they moved * [so] you would know that the type is actually Card, that Cardptr is simply a pointer to it, and that n is not a pointer. What is the reason for this?

编码人员编写声明的方式只是品味和风格的问题,两者都同样合理:

这会让我更喜欢 int *a 而不是 int* a:

int* a,b; // declares and int* and an int; illogical, right?

这会让我更喜欢 int* a 而不是 int *a:

int *a = 0; // a (an int*) is set to zero (a.k.a NULL), not *a; illogical, right?

现在,我的建议是:在这两种形式之间进行选择并坚持使用,始终如一。

关于c++ - 结构可以具有类型 `Card*` 吗? (书中的例子),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45991881/

相关文章:

syntax - YAML 语法验证器脚本

go - "i.(string)"在 golang 语法中的实际含义是什么?

php - 如何使用 post 请求将 C++ 数据发送到 PHP 以及允许发送的内容?

c++ - 如果 new 运算符失败,是否可以将指针设置为 null?

c - 在这个 C 谜题中要替换什么?

c++ - 整数初始化与使用指针初始化字符串,C++

c++ - 使用 "this"取消引用指针

c++ - 将 0 转换为 void

c++ - 返回右值时 VS2013 警告 C4172

python - Python while 语句中的 Else 子句