For example, in a project, there is a large amount of data structure, they are both two-way linked list, but I want to share a set of operational algorithms for the list, how to do it, there is no inheritance in C , otherwise I can inherit one Father (only two pointers in the class, one forward one backward), and its algorithm can be written in the virtual function in your class, the subsidiace is used. Such as:
Class Links {Public: Links * Back; Links * Forword;
Virtual add () {...}; virtual del () {...}; virtual ins () {...}; virtual print () = 0; ....
}
So we can: Class MyLinks: CHAR * MyName; CHAR SEX; Int Age; ... Virtual Print () {....
}; You can use the generic algorithm for your class.
How to do it in C? We can do it with the pointer and mandatory type of C.
Below is a small program I have summed up, reflecting the effect of this inheritage with the flexibility of the pointer: (I passed the GCC commissioning under Liniux)
========================================
#include
/ * Two-way linked list (similar to parent) * / typef struct hlinks {struct hlinks * bwlink; hlinks * fwlink;
/ * * A structure using a two-way linked list * (Similar to the subclass) * / typedef struct hant {hlinks links; int hdata; char key [10];
/ * * Bidirectional chain insertion gear algorithm (similar to member function in the parent) * / IF (HLINKS * ELEM, HLINKS * DEST) {if (! ELEM ||! DEST) Return;
ELEM-> BWLINK = DEST-> BWLINK; ELEM-> FWLINK = DEST; DEST-> bwlink-> fwlink = elem; dest-> bWLINK = ELEM;
/ * * Print (similar to a member function of subclass heavy-duty parent class) * / printLink (HLINKS * H) {Hent * P;
For (p = (haent *) h-> fwlink; / * <----------- turn hlink back * / p! = (hent *) h; p = (hent *) ( (HLINKS *) P) -> fwlink) {Printf ("HDATA = [% D], Key = [% s] / n", p-> hdata, p-> key);}}
MAIN () {hlinks head; haent a [4]; int I; head.bwlink = & head; head.fwlink = & head;
For (i = 0; i <4; i ) {a [i] .hdata = i * 10; sprintf (a [i] .key, "id =% D", i);
/ * Use generic algorithm to construct a bidirectional chain * / insert (hlinks *) & head); / * <----- Pay attention to this forced conversion * /}
PrintLink ((HLINKS *) & head); / * <------- pay attention to this forced conversion * /}
In fact, C is translated into c into C, compile, so compiling is slow. This action here may be similar to C to C. Everyone exchanges (litmouse@km169.net)
---- (All rights reserved, if you need to reprint, please indicate the source and author)