生活随笔
收集整理的這篇文章主要介紹了
C语言实现封装、继承、多态
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C語言實現(xiàn)封裝、繼承、多態(tài)
文章目錄
一. 封裝
C語言中雖然沒有類,但有struct和指針。我們可以在一個struct中存入數(shù)據(jù)和函數(shù)指針,以此來模擬類行為。
typedef struct _Parent
{int a
;int b
;void (*print
)(struct _Parent
*This
);}Parent
;
- 封裝性的意義在于,函數(shù)和數(shù)據(jù)是綁在一起的,數(shù)據(jù)和數(shù)據(jù)是綁在一起的。這樣,我們就可以通過簡單的一個結(jié)構(gòu)指針訪問到所有的數(shù)據(jù),遍歷所有的函數(shù)。封裝性,這是類擁有的屬性,當(dāng)然也是數(shù)據(jù)結(jié)構(gòu)體擁有的屬性。
二.繼承
- 如果要完全地用C語言實現(xiàn)繼承,可能有點難度。但如果只是簡單的做一下,保證子類中含有父類中的所有成員。這還是不難的。
typedef struct _Child
{ Parent parent
; int c
;
}Child
;
- 在設(shè)計C語言繼承性的時候,我們需要做的就是把基礎(chǔ)數(shù)據(jù)放在繼承的結(jié)構(gòu)的首位置即可。這樣,不管是數(shù)據(jù)的訪問、數(shù)據(jù)的強轉(zhuǎn)、數(shù)據(jù)的訪問都不會有什么問題。
三. 多態(tài)
- 這個特性恐怕是面向?qū)ο笏枷肜锩孀钣杏玫牧恕?/li>
- 要用C語言實現(xiàn)這個特性需要一點點技巧,但也不是不可能的。
#include <stdio.h>
#include <stdlib.h>
typedef struct A
{void *vptr
;int a
;int b
;void initA(A
*p
, int a
, int b
);void dong1();void dong2();
}A
;
void dong1()
{printf("基類 dong1\n");
}
void dong2()
{printf("基類 dong2\n");
}
typedef struct
{void(*v1
)();void(*v2
)();
}Vtable
;
Vtable A_Vtable
= { &dong1
, &dong2
};
void initA(A
*p
, int a
, int b
)
{p
->vptr
= &A_Vtable
;p
->a
= a
;p
->b
= b
;
}
typedef struct B
{A a
;int b
;void dong11();void dong66();void initB(B
* p
, int a
, int b
);
}B
;
void dong11()
{printf("派生類 dong11\n");
}
void dong66()
{printf("派生類 dong66\n");
}
typedef struct
{Vtable vtable
;void(*p
)();
}Vtable2
;
Vtable2 B_vtable
= { { &dong11
, &dong2
}, &dong66
};
void initB(B
* p
,int a
, int b
)
{p
->a
.vptr
= &B_vtable
; p
->b
= b
;
}
void test1()
{A aa
;initA(&aa
, 10, 20);((Vtable
*)aa
.vptr
)->v1();((Vtable
*)aa
.vptr
)->v2();
}
void test2()
{B
*b
= (B
*)malloc(sizeof(B
));initB(b
, 10, 20);A
*a
= (A
*)b
;((Vtable2
*)(a
->vptr
))->p();printf("\n------見證奇跡的時候到了,實現(xiàn)多態(tài)------\n\n");((Vtable
*)(a
->vptr
))->v1();((Vtable
*)(a
->vptr
))->v2();
}
void test3()
{B
*b
= (B
*)malloc(sizeof(B
));initB(b
, 10, 20);printf("%d\n", b
->a
.vptr
);printf("%d\n", ((A
*)b
)->vptr
);((Vtable
*)(b
->a
.vptr
))->v1(); ((Vtable
*)(b
->a
.vptr
))->v2();((Vtable2
*)(b
->a
.vptr
))->p();
}int main()
{test1();printf("---------------------------------------------\n\n");test2();printf("---------------------------------------------\n\n");test3();return 0;
}/*
**************************上面看著費勁
----光看下面就行了
typedef struct
{void(*v1
)();void(*v2
)();
}Vtable
;Vtable A_Vtable
= { &dong1
, &dong2
};typedef struct
{Vtable vtable
;void(*p
)();
}Vtable2
;Vtable2 B_vtable
= { { &dong11
, &dong2
}, &dong66
};所以,至始至終我們利用的就是Vtable2指向的函數(shù)。可以調(diào)用v1那是因為Vtable2中有Vtable,而Vtable中有v1
*/
總結(jié)
以上是生活随笔為你收集整理的C语言实现封装、继承、多态的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。