Default constructor in C

后端 未结 13 671
孤街浪徒
孤街浪徒 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:29

    You can write a function that returns the C struct:

    struct file create_file(int i, float f) {
        struct file obj = { i, f };
        // other code here...
        return obj;
    }
    

    If you wonder whether you can have "normal" member functions in C. Well, you can to some extent. I prefer the object-as-first-argument style. You pass a pointer to your struct as the first argument. This way, you can have several functions, defining the interface to your objects:

    int file_get_integer(struct file *self) { return self->i; }
    float file_get_float(struct file *self) { return self->f; }
    

    If you write in that style, what you have at the end is an abstract data-type. I've seen guys emulating the member function call syntax used in C++ by having function pointers into their struct and then doing:

    obj.get_integer(&obj);
    

    It's used by the linux kernel for defining the interface to file system drivers. It's a style of writing that one may like, or may not like. I don't like it too much, because i keep using members of structures for data and not for emulating member functions calls to look like in popular object oriented languages.

提交回复
热议问题