【问题标题】:Is it optional to use struct keyword before declaring a structure object?在声明结构对象之前是否可以使用 struct 关键字?
【发布时间】:2016-10-03 19:01:48
【问题描述】:

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

classname objectname;

结构体对象的声明方式一样吗?

喜欢

structname objectname;

我发现here一个结构对象声明为

struct Books Book1;

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

【问题讨论】:

  • 如果你不使用typedefstruct,编译器不知道structname是一个类型。
  • 在 C 中,你要么需要使用 struct 关键字,要么需要 typedef 结构类型。在 C++ 中,struct 关键字是可选的。
  • class object 不是 C 概念。
  • in struct Books book1; Books 不是“结构名”,是结构标签。

标签: c struct


【解决方案1】:

这是 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 * 作为参数。

【讨论】:

    【解决方案2】:

    你必须typedef他们来制作没有struct关键字的对象

    示例:

    typedef struct Books {
         char Title[40];
         char Auth[50];
         char Subj[100];
         int Book_Id;
    } Book;
    

    然后你可以定义一个没有struct关键字的对象,比如:

    Book thisBook;
    

    【讨论】:

    • 如果您不打算将自身内部的结构作为指针类型进行自我引用,则不需要Books 标签。
    • @Qix:使用Books标签的另一个原因是允许在不创建依赖关系的情况下从其他头文件中使用它。
    • @DietrichEpp 哦,对 :)
    【解决方案3】:

    是的。对于 C 语言,您需要明确给出变量的类型,否则编译器会抛出错误:'Books' undeclared。 (在上述情况下)

    因此,如果您使用 C 语言,则需要使用关键字 struct,但如果您使用 C++ 编写,则可以跳过此步骤。

    希望这会有所帮助。

    【讨论】:

    • 使用 g++ 意味着您实际上是在编写 C++,而不是 C。
    • 是的,但编译器驱动程序决定将代码链接到哪些库。所以我在编译器驱动的基础上进行了区分。
    • @RohitTakhar:但是如果您使用g++ 编译.c 文件,它将被编译并链接为C++,此时您只是在编写带有有趣扩展名的C++。
    • @DietrichEpp 对。我已经编辑了我的帖子以使其更清晰。
    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多