Let us consider an example. The following is the content of complex.c
:
#include <stdlib.h> #include "complex.h" struct complex { float r, i; }; void multComplex(void *x, void *y, void *product) { struct complex *cx = (struct complex *)x; struct complex *cy = (struct complex *)y; struct complex *cp = (struct complex *)product; cp->r = cx->r * cy->r - cx->i * cy->i; cp->i = cx->i * cy->r + cx->r * cy->i; } void *newComplex(float r, float i) { struct complex *pC; pC = (struct complex *)malloc(sizeof(struct complex)); pC->r = r; pC->i = i; return pC; } void delComplex(void *x) { struct complex *pC = (struct complex *)x; free(x); }
Note that complex.c
is the only file that knows the structure
of a struct complex
type. It has three subroutines defined,
one for creating a complex (newComplex
), one for
deleting a complex (delComplex
), and one for multiplying two
complex numbers (multComplex
).
The matching header file complex.h
would look like this:
void multComplex(void *, void *, void *); void *newComplex(float r, float i);
The header file does not mention anything about struct complex
,
at all. It only uses void pointers.
The user of the struct complex
type looks like the following:
#include "complex.h" int main(void) { void *a, *b, *c; a = newComplex(2,5); b = newComplex(-1,3); c = newComplex(0,0); multComplex(a,b,c); delComplex(a); delComplex(b); delComplex(c); }
Because the user only includes complex.h
, it does not have any
knowledge of the inside of a struct complex
. This makes it
impossible for the main program to modify a complex number because it
doesn't know how!
But why do we want to go through all the trouble to protect a data type
struct complex
? This permits the author of the complex number
module stay completely insulated from the users of the complex number
type, and vice versa. In fact, this mechanism allows the author of
the complex type to distribute just complex.h
and complex.o
(the object file of complex.c
). There is no need to distribute the
source code related to struct complex
, at all!
Copyright © 2006-08-28 by Tak Auyeung