我的讲师坚持认为以下是有效的 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/