1. 封裝
C語言中雖然沒有類,但有struct和指標,我們可以在一個struct中存入資料和函式指標,以此來模擬類行為,
typedef struct _Parent
{
int a;
int b;
void (*print)(struct _Parent *This);
}Parent;
封裝性的意義在于,函式和資料是綁在一起的,資料和資料是綁在一起的,這樣,我們就可以通過簡單的一個結構指標訪問到所有的資料,遍歷所有的函式,封裝性,這是類擁有的屬性,當然也是資料結構體擁有的屬性,
2.繼承
如果要完全地用C語言實作繼承,可能有點難度,但如果只是簡單的做一下,保證子類中含有父類中的所有成員,這還是不難的,
typedef struct _Child
{
Parent parent;
int c;
}Child;
在設計C語言繼承性的時候,我們需要做的就是把基礎資料放在繼承的結構的首位置即可,這樣,不管是資料的訪問、資料的強轉、資料的訪問都不會有什么問題,
3. 多型
這個特性恐怕是面向物件思想里面最有用的了,
要用C語言實作這個特性需要一點點技巧,但也不是不可能的,
我們使用上面定義的兩個結構體Parent, Child,簡單地描述了一個多型的例子,
#include <stdio.h>
#include <stdlib.h>
typedef struct _Parent
{
int a;
int b;
void (*print)(struct _Parent *This);
}Parent;
typedef struct _Child
{
Parent parent;
int c;
}Child;
void print_parent(Parent *This)
{
printf("a = %d. b = %d.\n", This->a, This->b);
}
void print_child(Parent *This)
{
Child *p = (Child *)This;
printf("a = %d. b = %d. c = %d.\n", p->parent.a, p->parent.b, p->c);
}
Parent *create_parent(int a, int b)
{
Parent *This;
This = NULL;
This = (Parent *)malloc(sizeof(Parent));
if (This != NULL)
{
This->a = a;
This->b = b;
This->print = print_parent;
printf("Create parent successfully!\n");
}
return This;
}
void destroy_parent(Parent **p)
{
if (*p != NULL)
{
free(*p);
*p = NULL;
printf("Delete parent successfully!\n");
}
}
Child *create_child(int a, int b, int c)
{
Child *This;
This = NULL;
This = (Child *)malloc(sizeof(Child));
if (This != NULL)
{
This->parent.a = a;
This->parent.b = b;
This->c = c;
This->parent.print = print_child;
printf("Create child successfully!\n");
}
return This;
}
void destroy_child(Child **p)
{
if (*p != NULL)
{
free(*p);
*p = NULL;
printf("Delete child successfully!\n");
}
}
int main()
{
Child *p = create_child(1, 2, 3);
Parent *q;
q = (Parent *)p;
q->print(q);
destroy_child(&p);
system("pause");
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/71536.html
標籤:C
上一篇:C語言基本資料型別的轉換
下一篇:C語言指向函式的指標
