null
vuild_
Nodes
Flows
Hubs
Login
MENU
Notifications
Login
☆ Star
OOP in C
#c
#c-lang
#advanced
#design-patterns
#oop
@devpc
|
2026-03-29 13:49:35
|
GET /api/v1/nodes/85?nv=1
History:
v1 (2026-03-29) (Latest)
0
Views
0
Calls
# OOP in C > 구조체+함수 포인터로 객체지향 흉내내기 ## 학습 목표 - 구조체와 함수 포인터로 클래스 개념을 구현한다 - 캡슐화, 상속, 다형성을 C로 모사하는 패턴을 익힌다 ## 내용 ### 캡슐화 (Encapsulation) ```c // "클래스" 정의 typedef struct Animal { char name[32]; int age; // "메서드"를 함수 포인터로 void (*speak)(struct Animal *self); void (*describe)(struct Animal *self); } Animal; // 메서드 구현 void animal_describe(Animal *self) { printf("%s (나이: %d)\n", self->name, self->age); } // 생성자 Animal animal_new(const char *name, int age, void (*speak)(Animal *)) { Animal a; strncpy(a.name, name, sizeof(a.name) - 1); a.age = age; a.speak = speak; a.describe = animal_describe; return a; } ``` ### 다형성 (Polymorphism) ```c void dog_speak(Animal *self) { printf("%s: 멍멍!\n", self->name); } void cat_speak(Animal *self) { printf("%s: 야옹!\n", self->name); } void duck_speak(Animal *self) { printf("%s: 꽥꽥!\n", self->name); } int main() { Animal animals[] = { animal_new("강아지", 3, dog_speak), animal_new("고양이", 5, cat_speak), animal_new("오리", 2, duck_speak), }; // 같은 인터페이스로 다른 동작 → 다형성 for (int i = 0; i < 3; i++) animals[i].speak(&animals[i]); return 0; } ``` ### 상속 모사 (Inheritance) ```c // 부모 구조체를 첫 번째 필드로 포함 typedef struct { Animal base; // ← Animal을 "상속" char breed[32]; } Dog; Dog dog_new(const char *name, int age, const char *breed) { Dog d; d.base = animal_new(name, age, dog_speak); strncpy(d.breed, breed, sizeof(d.breed) - 1); return d; } // Animal * 로 업캐스팅 가능 Animal *a = (Animal *)&dog; a->speak(a); ``` ## 참고 - 이 패턴은 Linux 커널, GTK 등 대형 C 프로젝트에서 실제로 사용된다 - C++의 vtable과 동일한 원리로 동작한다
// COMMENTS
ON THIS PAGE