bonjour.

En m'inspirant des tutoriels j'ai écrit un exemple de programmation orienté objet en C. J'ai ajouté une manière de faire de l'héritage.

J'aimerai connaître votre sentiment à propos de ce code :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <stdio.h>
#include <stdlib.h>
 
typedef enum {MALE, FEMELLE} SEXE;
 
#define HUMAN(identity) identity->human
 
typedef struct Human
{
  /* Destructeur */
  void (*delete)(struct Human **this);
 
  /* Méthodes d'accès aux données internes */
  void (*set_sexe) (struct Human *this, SEXE sexe);
  SEXE (*get_sexe) (struct Human *this);
 
  /* Données internes */
  char sexe;
} Human;
 
typedef struct Identity
{
  Human *human;
 
  /* Destructeur */
  void (*delete)(struct Identity **this);
 
  /* Données internes */
  char *name;
  unsigned char age;
  unsigned char size;
} Identity;
 
static void
human_delete (Human **this)
{
  if (!this) return;
  free (*(this));
  *(this) = NULL;
}
 
static void
human_set_sexe (Human *this, SEXE sexe)
{
  this->sexe = sexe;
}
 
static SEXE
human_get_sexe (Human *this)
{
  return this->sexe;
}
 
Human*
human_new()
{
  Human *this;
 
  this = malloc (sizeof(Human));
  if (!this)
    {
      fprintf (stderr, "Allocation memory error in human_new();\n");
      exit (1);
    }
  /* Affectation des méthodes */
  this->delete = human_delete;
  this->set_sexe = human_set_sexe;
  this->get_sexe = human_get_sexe;
 
  /* Initialisation des variables internes */
  this->sexe = MALE;
 
  return this;
}
 
static void
identity_delete (Identity **this)
{
  if (!this) return;
  Identity *identity = *this;
 
  /* Libération de l'être humain */
  HUMAN(identity)->delete (&HUMAN(identity));
 
  free (*(this));
  *(this) = NULL;
}
 
Identity*
identity_new ()
{
  Identity *this;
 
  this = malloc (sizeof(Identity));
  if (!this)
    {
      fprintf (stderr, "Allocation memory error in identity_new();\n");
      exit (1);
    }
 
  /* Allocation d'un nouvelle être humain */
  this->human = human_new ();
 
  /* Affectation des méthodes */
  this->delete = identity_delete;
 
  return this;
}
 
int
main(int argc, char *argv[])
{
  Identity *identity = NULL;
 
  identity = identity_new();
 
  HUMAN(identity)->set_sexe (HUMAN(identity), FEMELLE);
 
  switch (HUMAN(identity)->get_sexe(HUMAN(identity)))
    {
    case MALE:
      printf("La personne est de sexe masculin\n");
      break;
    default:
      printf ("La personne est de sexe feminin\n");
      break;
    }
 
  identity->delete (&identity);
  return 0;
}