Default constructor in C

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

    C++ is different from C in this case in the respect that it has no "classes". However, C (as many other languages) can still be used for object oriented programming. In this case, your constructor can be a function that initializes a struct. This is the same as constructors (only a different syntax). Another difference is that you have to allocate the object using malloc() (or some variant). In C++ you would simlpy use the 'new' operator.

    e.g. C++ code:

    class A {
      public:
        A() { a = 0; }
        int a;
    };
    
    int main() 
    {
      A b;
      A *c = new A;
      return 0;
    }
    

    equivalent C code:

    struct A {
      int a;
    };
    
    void init_A_types(struct A* t)
    {
       t->a = 0;
    }
    
    int main()
    {
       struct A b;
       struct A *c = malloc(sizeof(struct A));
       init_A_types(&b);
       init_A_types(c);
       return 0;
    }
    

    the function 'init_A_types' functions as a constructor would in C++.

提交回复
热议问题