C 언어의 데이터 은닉 캡슐화
C++에서는 데이터 구조를 숨기고 사용자에게 인터페이스만 제공하려면, 인터페이스 클래스를 상속·구현하는 방식으로 목적을 이룰 수 있다. 그렇다면 C에서는 어떤 방식을 쓸 수 있을까. 아래에 예가 있다:
// demo.h
#ifndef DEMO_H
#define DEMO_H
typedef struct Demo* Demo;
extern Demo DemoCreate(int num);
extern void DemoDestory(Demo demo);
extern void DemoShow(Demo demo);
#endif//DEMO_H
// demo.c
#include "demo.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct Demo_ {
int num_;
} Demo_;
Demo DemoCreate(int num) {
Demo_* demo = (Demo_*)malloc(sizeof(Demo_));
demo->num_ = num;
return (Demo)demo;
}
void DemoDestory(Demo demo) {
free(demo);
}
void DemoShow(Demo demo) {
printf("%d\n", ((Demo_*)demo)->num_);
}
// main.c
#include "demo.h"
int main() {
Demo demo = DemoCreate(777);
DemoShow(demo);
DemoDestory(demo);
return 0;
}