Advertisement
amigojapan

using structs as kinda classes in C

Jan 17th, 2017
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. struct Person {
  4.     char name[100];
  5.     int age;
  6.     void (*connect_methods)(struct Person *);//guess I coudl get rid of this and just use a function but somehow it seems nice to use a methodd to connect other methods, but usig a function would reduce the number of lines of code
  7.     void (*increment_age)(struct Person *);
  8.     void (*print_me)(struct Person *);
  9. };
  10.  
  11. void increment_age(struct Person *self) {
  12.     self->age++;
  13. }
  14. void print_me(struct Person *self) {
  15.     printf("\nname:%s\nage%i\n",self->name,self->age);
  16. }
  17.  
  18. void connect_methods(struct Person *self) {
  19.     self->increment_age=&increment_age;
  20.     self->print_me=&print_me;
  21.    
  22. }
  23. int main(int argc, const char * argv[]) {
  24.     struct Person p1;
  25.     strcpy(p1.name,"Jhon Doe");
  26.     p1.age=22;
  27.     p1.connect_methods=&connect_methods;
  28.     p1.connect_methods(&p1);
  29.    
  30.     struct Person p2;
  31.     strcpy(p2.name,"Marry Joan");
  32.     p2.age=33;
  33.     p2.connect_methods=&connect_methods;
  34.     p2.connect_methods(&p2);
  35.    
  36.     p1.increment_age(&p1);
  37.     p1.print_me(&p1);
  38.     p2.increment_age(&p2);
  39.     p2.print_me(&p2);
  40.     printf("end\n");
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement