c++ - "struct type variablename"作为声明有效吗?

标签 c++ syntax

我的讲师坚持认为以下是有效的 C++ 语句,这让我感到惊讶:

struct charlistrecord *next

在C/C++中声明递归数据类型时发现完整的条件如下:

typedef struct charlistrecord
{
     char data;
     struct charlistrecord *next;
} *charlist;

我想知道是否曾经有一段时间这种语法被接受,或者我是否只是愚蠢地认为我了解 C++。

最佳答案

在 C++ 和 typedef 的假设之前,获取类型结构的唯一方法是通过此语法,并且这是获取自类型链接节点的唯一方法。

struct Foo
{
    int val;
    struct Foo *link;
};

在 C 语言中,这要求 Foo 的任何用法都是:

struct Foo foo;
struct Foo *foo_ptr;

等等..

typedef 通过这样做来帮助解决这个问题:

typedef struct Foo
{
   int val;
   struct Foo *link;
} Foo;

从现在起你可以这样做:

Foo foo;       // same as struct Foo
Foo *foo_ptr;  // same as struct Foo *

注意:使用 typedef 为 struct Name 起别名并不限于 Name 作为别名。你这样做也是完全正确的:

typedef struct Foo
{
    int val;
    struct Foo *link;
} Bar;

现在可以执行以下操作;

struct Foo foo;
Bar bar;
struct Foo *fooptr = &bar;
Bar *barptr = &foo;

真的让你希望自己以前是用 C 语言编程的,不是吗?可能还没有把事情弄清楚,但希望能少一点灰色。

关于c++ - "struct type variablename"作为声明有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13286865/

相关文章:

c++ - x264 NALU 序列化和处理

c++ - 原型(prototype)声明和前向声明之间的区别?

swift 字典 : join key and value into string

parsing - 你能修改这个 BNF 语法以始终包含奇数只狗吗?

c++ - 如何正确使用结构中的 const 字符串指针?

c++ - 如何从函数返回 std::optional<myclass>?

AngularJS - 指令 - 以下语法背后的原因是什么?

c - 嵌套 IF-ELSE 之前的 IF 语句

c++ - 保护我的程序免受 RE 侵害

emacs - 在Emacs中更改CamelCase单词的前向单词/后向单词/kill-word