C語言實現封裝、繼承和多態


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;  
  
}  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM