C: Good Habits re: Transitioning to C++

后端 未结 13 593
梦毁少年i
梦毁少年i 2020-12-13 02:47

I\'ve been learning C at Varsity for just shy of 2months now, and next year we\'ll be moving on to C++.

Are there any habits I should get into with my C programmin

相关标签:
13条回答
  • 2020-12-13 03:35

    Use structures and function pointers as much as possible to mimic the methods of the classes and the abstract methods.

    For example, if you want to define a vehicle, and a car derived from vehicle using C, you would write (sorry, I won't check the code :-) ):

    struct Vehicle
      {
      void (*checkFuel)(Vehicle*);
      void (*start)(Vehicle*);
      void (*move)(Vehicle*);
      void (*stop)(Vehicle*);
      }
    
    void start1(Vehicle* v)
      {
      v->checkFuel(v);
      printf("START!");
      }
    
    void start2(Vehicle* v)
      {
      v->checkFuel(v);
      printf("VROOOOMM!");
      }
    
    
    struct Car
      {
      Vehicule base;
      int (*klaxon)(Car*);
      }
    
    Vehicule* newVehicule()
     {
     Vehicule* v=(Vehicule*)malloc(sizeof(Vehicule));
     v->start= start1;
     v->move=
     (...)
     return v;
     }
    
    
    Car* newCar()
     {
     Car* c=(Car*)malloc(sizeof(Car));
     Vehicule* v=(Vehicule*)c;
     v->start= start2;
     v->move=
     (...)
     c->kaxon=(...)
     return c;
     }
    
    0 讨论(0)
提交回复
热议问题