Data Hiding in C
In C++, if we want to hide the data structure, we can only provide an interface for the user, which can be achieved by achieving the inheritance interface type. So, what's in C? The following is one example:
// 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;
}