c - 在声明结构对象之前是否可以选择使用 struct 关键字?

标签 c struct

要声明一个类对象,我们需要格式

classname objectname;

声明一个结构体对象也是这样吗?

喜欢

structname objectname;

我找到了 here声明为的结构对象

struct Books Book1;

其中 Books 是结构名,Book1 是它的对象名。那么在声明结构对象之前是否需要使用关键字struct

最佳答案

这是C和C++的区别之一。

在 C++ 中,当您定义一个类时,您可以使用带或不带关键字 class(或 struct)的类型名称。

// Define a class.
class A { int x; };

// Define a class (yes, a class, in C++ a struct is a kind of class).
struct B { int x; };

// You can use class / struct.
class A a;
struct B b;

// You can leave that out, too.
A a2;
B b2;

// You can define a function with the same name.
void A() { puts("Hello, world."); }

// And still define an object.
class A a3;

在C中,情况就不同了。类不存在,取而代之的是结构。但是,您可以使用 typedef。

// Define a structure.
struct A { int x; };

// Okay.
struct A a;

// Error!
A a2;

// Make a typedef...
typedef struct A A;

// OK, a typedef exists.
A a3;

与函数或变量同名的结构并不少见。例如,POSIX 中的 stat() 函数将 struct stat * 作为参数。

关于c - 在声明结构对象之前是否可以选择使用 struct 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39838629/

相关文章:

c - 如何使用递归删除数组中的相邻重复项?

c - 获取成员请求不是结构或 union 错误

c# - 我们可以对结构布局做出假设吗?

c++ - 空结构定义在 C 中是非法的,但在 C++ 中不是?

c - 指向结构指针的空指针

c - 了解包含自身类型指针的结构

c++ - 原始数据(字节)和有符号/无符号变量

c - 在 C 中将整数除以 2 的幂

c - 使用 ualarm 的问题

c - 为什么我在 C 中分配矩阵时得到十六进制值?