C言語シミュレーションC++虚関数多様性

4507 ワード

どのようにC言語を使ってC++の多態を実現しますか?
これは私がエンドウの莢の面接を受けたときに試験官が聞いた問題で、私は当初答えなかった.これまでこのような問題を考えたことがないからだ.
以下の内容は転載したブログで、これをクリックして原文を調べます.
従来の円と正方形の問題を例にとると、ベースクラスはShapeであり、各クラスは虚関数showShape()を定義し、多態を体現する.
大体思想はすべての構造体の頭がすべて同じで(ある基類として)、このように構造体の頭の針でいかなる構造体を指すことができて、虚関数はこの構造体の頭の上で文章をして、コードを見て、注釈はとても詳しいです.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85 #include <malloc.h> #include <stdio.h>     // 2 enum ShapeType {CIRCLE, SQUARE};     // ,calculate , typedef void (*show)(); typedef double (*calculate)( int arg);     // typedef struct _VirtualFun {   show showShape;   calculate calArea; } VirtualFun,*pVirtualFun;     // ,Shape typedef struct _Shape {   ShapeType type;   VirtualFun *pfun; }Shape,*ShapePointer;     // ,Circle typedef struct _Circle {   Shape itsType;   int r; }Circle;     // ,Square typedef struct _Square {   Shape itsType;   int d; }Square;     // void showCircle() {   printf ( "I'm circle
"
); }     // void showSquare() {   printf ( "I'm square
"
); }     //circle Circle circle ={   CIRCLE,   (pVirtualFun) malloc ( sizeof (VirtualFun)),   0 };     //square Square square ={   SQUARE,   (pVirtualFun) malloc ( sizeof (VirtualFun)),   0 }; // , ShapePointer。 void virtualShow(ShapePointer sp) {   sp->pfun->showShape(); }     void main() {   //   circle.itsType.pfun->showShape = showCircle;   square.itsType.pfun->showShape = showSquare;       //   ShapePointer spc = (ShapePointer)&circle;   ShapePointer sps = (ShapePointer)&square;       // , 。   virtualShow(spc);   virtualShow(sps);   getchar (); }
出力結果:
I'm circle
I'm square