Default constructor in C

后端 未结 13 721
孤街浪徒
孤街浪徒 2020-12-07 21:02

Is there a way to have some kind of default constructor (like a C++ one) for C user types defined with a structure?

I already have a macro which works like a fast in

13条回答
  •  长情又很酷
    2020-12-07 21:37

    Using functions to create and dispose of structures has already been mentioned. But in a comment you mentioned that you wanted a "default constructor" - I think you mean that you want to initialize some (all?) of the struct fields to default values.

    This is done in C using some coding convention -- either functions, macros, or a mix. I usually do it something like the following --

    struct some_struct {
        int a;
        float b;
    };
    #define some_struct_DEFAULT { 0, 0.0f}
    struct some_struct *some_struct_create(void) {
        struct some_struct *ptr = malloc(sizeof some_struct);
        if(!ptr)
            return ptr;
    
        *ptr = some_struct_DEFAULT;
        return ptr;
    }
    // (...)
    struct some_struct on_stack = some_struct_DEFAULT;
    struct some_struct *on_heap = some_struct_create();
    

提交回复
热议问题