The inheritance mentioned here is a bit like the parent class and subclass in C ++. In fact, it is a forced conversion of the struct type. Recently, we often see this method when looking at the Linux kernel source code, here we will consider it as a simple learning.
The following is a demo. It is very simple. A father struct and a son struct are defined respectively. The father struct defines two integer variables, the first member in the son struct is a variable of the father struct type, and the other two members in son are also Integer Variables. In this way, the son struct is like inheriting the father struct, and added two members. The Code is as follows:
1 # include <stdio. h> 2 3 // parent struct 4 struct father 5 {6 int F1; 7 int F2; 8 }; 9 10 // child struct 11 struct son12 {13 // define a parent struct variable in the Child struct, which must be placed first in the Child struct 14 struct father FN; 15 // child struct extension variable 16 int S1; 17 int S2; 18}; 19 20 void test (struct son * t) 21 {22 // forcibly convert the child struct pointer to the parent struct pointer 23 struct father * f = (struct father *) T; 24 // print the original value 25 printf ("F-> F1 = % d \ n", F-> F1 ); 26 printf ("F-> F2 = % d \ n", F-> F2); 27 // modify the original value 28 F-> F1 = 30; 29 F-> F2 = 40; 30} 31 32 int main (void) 33 {34 struct son s; 35 S. FN. f1 = 10; 36 s. FN. f2 = 20; 37 38 test (& S); 39 // print the modified value 40 printf ("s. FN. f1 = % d \ n ", S. FN. f1); 41 printf ("s. FN. f2 = % d \ n ", S. FN. f2); 42 43 return 0; 44}
Here, the key is to put the father type variables first in the son struct. Running effect:
Modify the son struct so that the father type variables are not placed first in the son structure. The modification is as follows:
1 // child struct 2 struct son3 {4 // extension variable of child struct 5 Int S1; 6 int S2; 7 struct father FN; 8 };
Modified running effect:
Summary:
This method is useful for struct extension.