fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct _Animal Animal;
  5. struct _Animal {
  6. const char *name;
  7. void (*play)(Animal *);
  8. };
  9.  
  10. typedef struct _Dog Dog;
  11. struct _Dog {
  12. Animal animal;
  13. };
  14.  
  15. void playDog(Animal *dog) {
  16. printf("わんわん!%sだよ\n", ((Dog *)dog)->animal.name);
  17. }
  18.  
  19. Animal *newDog(const char *name) {
  20. Dog *dog = (Dog *)malloc(sizeof(Dog));
  21. dog->animal.name = name;
  22. dog->animal.play = playDog;
  23.  
  24. return (Animal *)dog;
  25. }
  26.  
  27. typedef struct _Cat Cat;
  28. struct _Cat {
  29. Animal animal;
  30. int sleep;
  31. };
  32.  
  33. void playCat(Animal *cat) {
  34. printf("にゃあ!%sだよ\n", ((Cat *)cat)->animal.name);
  35. if(((Cat *)cat)->sleep == 1) {
  36. printf("...でも寝る\n");
  37. }
  38. }
  39.  
  40. Animal *newCat(const char *name, int sleep) {
  41. Cat *cat = (Cat *)malloc(sizeof(Cat));
  42. cat->animal.name = name;
  43. cat->animal.play = playCat;
  44. cat->sleep = sleep;
  45.  
  46. return (Animal *)cat;
  47. }
  48.  
  49. int main(int argc, char *argv[])
  50. {
  51. int i;
  52. Animal *pets[] = {
  53. newDog("ぽち"),
  54. newCat("たま", 1)
  55. };
  56.  
  57. for(i = 0; i < (sizeof pets / sizeof pets[0]); i++) {
  58. pets[i]->play(pets[i]);
  59. }
  60.  
  61. for(i = 0; i < (sizeof pets / sizeof pets[0]); i++) {
  62. free(pets[i]);
  63. }
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
わんわん!ぽちだよ
にゃあ!たまだよ
...でも寝る