Encapsulation is the packaging of data and functions into a class, which most C programmers already have.
In C standard library, fopen(), fclose(), fread(), fwrite() and other functions operate on FILE. The data content is FILE, the data reads and writes are fread() and fwrite(), fopen() is analogous to the constructor, and fclose() is the destructor.
This may seem obvious, but let’s implement the basic encapsulation features.
#ifndef SHAPE_H
#define SHAPE_H
#include <stdint.h>
// Shape attributes
typedef struct {
int16_t x;
int16_t y;
} Shape;
// Shape operation function, interface function
void Shape_ctor(Shape * const me, int16_t x, int16_t y);
void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
int16_t Shape_getX(Shape const * const me);
int16_t Shape_getY(Shape const * const me);
#endif /* SHAPE_H */
Copy the code
This is the Shape declaration, and it’s very simple and easy to understand. You usually put the declaration in a header file called shape.h. Let’s take a look at the Shape definition, which is in “shape.c”.
#include "shape.h"
// constructor
void Shape_ctor(Shape * const me, int16_t x, int16_t y)
{
me->x = x;
me->y = y;
}
void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy)
{
me->x += dx;
me->y += dy;
}
// Get the attribute value function
int16_t Shape_getX(Shape const * const me)
{
return me->x;
}
int16_t Shape_getY(Shape const * const me)
{
return me->y;
}
Copy the code
Look at the main. C
#include "shape.h" /* Shape class interface */
#include <stdio.h> /* for printf() */
int main(a)
{
Shape s1, s2; /* multiple instances of Shape */
Shape_ctor(&s1, 0.1);
Shape_ctor(&s2, - 1.2);
printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1));
printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2));
Shape_moveBy(&s1, 2.4 -);
Shape_moveBy(&s2, 1.2 -);
printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1));
printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2));
return 0;
}
Copy the code
Execution Result:
Shape s1(x=0,y=1)
Shape s2(x=- 1,y=2)
Shape s1(x=2,y=- 3)
Shape s2(x=0,y=0)
Copy the code
The whole example, very simple, very easy to understand. In the future, when writing code, we should think more about the standard library file IO operation, so as to consciously cultivate object-oriented programming thinking.
Free C study kit