C 로 하는 OOP
Sun, Jan 15 2023 05:25:57아래 코드에서는 OOP의 핵심을 다루고 있습니다. 아래 코드를 이해하고 자유자재로 활용할 수 있다면 C 언어로도 얼마든지 객체 지향 프로그래밍을 할 수 있습니다.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*Animal 은 interface 역할을 할 수 있습니다 */
typedef struct _Animal Animal;
struct _Animal
{
void (*print) (Animal *animal);
};
/* Animal 을 상속받은 객체를 공통 interface 를 통하여 다룰 수 있습니다 */
void animal_print (Animal *animal)
{
if (animal->print)
animal->print (animal);
}
typedef struct _Cat Cat;
struct _Cat
{
/* Animal 을 상속 */
Animal base;
char *name;
};
typedef struct _Dog Dog;
struct _Dog
{
/* Animal 을 상속 */
Animal base;
char *name;
};
/* 멤버 함수 */
void cat_print (Animal *animal)
{
Cat *cat = (Cat*) animal;
printf ("%s: 야옹\n", cat->name);
}
/* 생성자 */
Cat *cat_new (char *name)
{
Cat *cat = malloc (sizeof (Cat));
cat->base.print = cat_print;
cat->name = strdup (name);
return cat;
}
/* 소멸자 */
void cat_free (Cat *cat)
{
free (cat->name);
free (cat);
}
/* 멤버 함수 */
void dog_print (Animal *animal)
{
Dog *dog = (Dog*) animal;
printf ("%s: 멍멍\n", dog->name);
}
/* 생성자 */
Dog *dog_new (char *name)
{
Dog *dog = malloc (sizeof (Dog));
dog->base.print = dog_print;
dog->name = strdup (name);
return dog;
}
/* 소멸자 */
void dog_free (Dog *dog)
{
free (dog->name);
free (dog);
}
int main ()
{
Cat *cat = cat_new ("고양이");
Dog *dog = dog_new ("멍멍이");
/* 아래의 호출들은 동일한 결과를 보여줍니다. 다양한 방법으로 호출할 수 있습니다 */
animal_print ((Animal*) cat); /* 고양이: 야옹 */
animal_print ((Animal*) dog); /* 멍멍이: 멍멍 */
cat->base.print ((Animal*) cat); /* 고양이: 야옹 */
dog->base.print ((Animal*) dog); /* 멍멍이: 멍멍 */
Animal *animal;
animal = (Animal*) cat;
animal->print (animal); /* 고양이: 야옹 */
animal = (Animal*) dog;
animal->print (animal); /* 멍멍이: 멍멍 */
cat_free (cat);
dog_free (dog);
return 0;
}