C語言也能面向對象?不是C++是面向對象的么?其實C語言也能抽象成簡單的面向對象方法,在Linux內核源碼當中,底層的驅動代碼、文件系統等皆采用了面向對象的封裝技術,這樣的好處是將客觀的東西抽象出來,以接口的方式管理。
C++完全包容C語言的語法特點,C++中類:class和C語言中的結構體:struct是等效的,不過C++是一種完全面向對象的模式,其中域、對象名,都封裝在類里面,而C語言沒有明確規定,只是結構體是一種根據設計需要來構造的一種特殊的數據類型。C++中每個類都提供一個默認的構造函數和析構函數(當然也可以自定義一個構造函數)。下面是用純C語言實現一個C++的vector容器:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4 #include <string.h>
5 typedef int DataType; 6 typedef struct array 7 { 8 DataType *Data; 9 int size,max_size; 10 void (*Constructor)(struct array *);//構造函數
11 void (*Input)(DataType ,struct array *);//輸入數據
12 int (*get_array_size)(struct array *);//獲取arr的大小
13 int (*return_index_value)(struct array *,int);//返回下標為index的值
14 void (*print)(struct array *);//打印結果
15 void (*Destructor)(struct array *);//析構函數
16 }Array; 17
18 void Init(Array *this); 19 void _print(struct array *this); 20 void _constructor(Array *this); 21 void _denstructor(Array *this); 22 void _input(DataType data,Array *this); 23 int _get_szie(Array *this); 24 int _return_index_value(Arrary *this,int index); 25
26 void Init(Array *this) 27 { 28 this->Input =_input; 29 this->print =_print; 30 this->get_array_size = _get_size; 31 this->return_index_value = _return_index_value; 32 this->Constructor =_constructor; 33 this->Destructor =_denstructor; 34 this->Constructor(this); 35 } 36
37 void _constructor(Array *this) 38 { 39 this->size=0; 40 this->max_size=10; 41 this->Data=(DataType *)malloc(this->max_size*sizeof(DataType)); 42 memset(this->Data,0,10); 43 } 44
45 void _input(DataType data, Array *this) 46 { 47 int i; 48 DataType *ptr; 49
50 if(this->size >= this->max_size) 51 { 52 this->max_size +=10; 53 ptr=(DataType *)malloc(this->max_size*sizeof(DataType)); 54 for(i=0;i<this->size;i++) 55 ptr[i]=this->Data[i]; 56 free(this->Data); 57 this->Data=ptr; 58 } 59 this->Data[this->size]=data; 60 this->size +=1 ; 61 } 62
63 void _print(struct array *this) 64 { 65 assert(this != NULL); 66 struct array *ptr=this; 67 int i=0; 68 for(i=0;i<ptr->size;i++) 69 printf("data is %d\n",ptr->Data[i]); 70
71 return ; 72 } 73 int _get_array_size(Array *this) 74 { 75 assert(this != NULL); 76 return this->size+1; 77 } 78 int _return_index_value(Array *this,int index) 79 { 80 assert(this != NULL); 81 return (this->Data[index]); 82 } 83 void _denstructor(Array *this) 84 { 85 int i=0; 86 assert(this != NULL); 87 for(i=0;i<this->max_size;i++) 88 this->Data[i]=0; 89 free(this->Data); 90 } 91
92 int main() 93 { 94 Array MyArray; 95
96 Init(&MyArray); //使用對象前必須初始化,間接調用構造函數 97 // MyArray.Data[]={1,2,3,4,5};
98 MyArray.Input(1,&MyArray); 99 MyArray.Input(2,&MyArray); 100 MyArray.Input(3,&MyArray); 101 MyArray.Input(4,&MyArray); 102 MyArray.Input('5',&MyArray); 103 MyArray.print(&MyArray); 104 printf("the array size is :%d\n",MyArray.get_array_size(&MyAarray)); 105 printf("the index value in array is:%d\n",MyArray.return_index_value(&MyArray,3)); 106 MyArray.Destructor(&MyArray); //使用對象后必須顯式調用析構函數
107
108 return 0; 109 }