Is it optional to use struct keyword before declaring a structure object?

前端 未结 3 715
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 08:40

To declare a class object we need the format

classname objectname;

Is it the sameway to declare a structure object?

like



        
相关标签:
3条回答
  • 2020-12-10 08:55

    You have to typedef them to make objects without struct keyword

    example:

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

    Then you can define an object without the struct keyword like:

    Book thisBook;
    
    0 讨论(0)
  • 2020-12-10 09:13

    Yes. In case of C language, you need to explicitly give the type of the variable otherwise the compiler will throw an error: 'Books' undeclared.(in the above case)

    So you need to use keyword struct if you are using C language but you can skip this if you are writing this in C++.

    Hope this helps.

    0 讨论(0)
  • 2020-12-10 09:15

    This is one of the differences between C and C++.

    In C++, when you define a class you can use the type name with or without the keyword class (or 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;
    

    In C, the situation is different. Classes do not exist, instead, there are structures. You can, however, use typedefs.

    // 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;
    

    It is not uncommon to encounter structures with the same names as functions or variables. For example, the stat() function in POSIX takes a struct stat * as an argument.

    0 讨论(0)
提交回复
热议问题