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

前端 未结 3 716
爱一瞬间的悲伤
爱一瞬间的悲伤 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 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.

提交回复
热议问题