c 语言程序设计阚道宏,C语言用宏实现静态多态
綜述
多態(tài)性是面向?qū)ο蟪绦蛟O(shè)計(jì)的一個(gè)重要特征。
在C++語言中,多態(tài)指的是:具有不同功能的函數(shù)可以用同一個(gè)函數(shù)名,可以用一個(gè)函數(shù)名調(diào)用不同內(nèi)容的函數(shù)。
C++的多態(tài)分為兩種:
1. 靜態(tài)多態(tài)性(編譯時(shí)多態(tài)):在程序編譯時(shí)系統(tǒng)就能決定調(diào)用的是哪個(gè)函數(shù),因此稱為編譯時(shí)多態(tài)性
2. 動(dòng)態(tài)多態(tài)性:在程序運(yùn)行過程中才動(dòng)態(tài)確定操作指針指向的對(duì)象,又被稱為運(yùn)行時(shí)多態(tài)
C++實(shí)現(xiàn)多態(tài)可以用虛函數(shù),抽象類,覆蓋以及模板實(shí)現(xiàn)
C語言是面向過程的語言,但同樣可以實(shí)現(xiàn)多態(tài)性,可以通過宏實(shí)現(xiàn)編譯時(shí)多態(tài),用函數(shù)指針實(shí)現(xiàn)動(dòng)態(tài)多態(tài)
C語言用宏實(shí)現(xiàn)編譯時(shí)多態(tài)
例如以下例子是用宏實(shí)現(xiàn)雙向鏈表的一部分
#include
#include
#define INIT_LIST_TYPE(type) ? ? ? ? ? ? ? ? ? ?\
typedef struct list_element_##type { ? ? ? ?\
struct list_element_##type* next, *pre; \
void* val; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?\
} list_element_##type; ? ? ? ? ? ? ? ? ? ? ?\
typedef struct list_head_##type { ? ? ? ? ? \
list_element_##type* elem, *last; ? ? ? \
int length; ? ? ? ? ? ? ? ? ? ? ? ? ? ? \
} list_head_##type;
#define list_element(type) \
list_element_##type
#define list_head(type) \
list_head_##type
#define LIST_FUNC_DECLARE(type) ? \
list_head_##type* init_list_##type();
#define LIST_FUNC_INIT(type) ? \
_init_list(type)
#define init_list(type) init_list_##type()
#define _init_list(type) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?\
list_head_##type* init_list_##type() ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?\
{ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? \
list_head_##type* h = (list_head_##type*)calloc(1, sizeof(list_head_##type)); \
h->last = h->elem = NULL; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? \
h->length = 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?\
return h; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? \
}
#endif
調(diào)用
INIT_LIST_TYPE(int);
LIST_FUNC_INIT(int);
INIT_LIST_TYPE(float);
LIST_FUNC_INIT(float);
#define context_bam_elem list_element(int)
#define list_head_t list_head(int)
#define list_element_f_t list_element(float)
#define list_head_f_t list_head(float)
int main()
{
list_head_t* h = init_list(int);
list_head_f_t* h1 = init_list(float);
return 0;
}
---------------------
作者:晏九
來源:CSDN
原文:https://blog.csdn.net/weixin_42670653/article/details/81385745
版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請(qǐng)附上博文鏈接!
總結(jié)
以上是生活随笔為你收集整理的c 语言程序设计阚道宏,C语言用宏实现静态多态的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 年底离职潮拿什么留住你的员工 公司的管理
- 下一篇: 开通唯品花的条件