gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:17:52 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com