c與面象對象之繼承

        c語言是面過程的語言,不過可以通過結構體編寫出具有類似對象的結構化程序。本以爲c語言只能進行類似對象的封裝,今天在<<Linux C編程實戰>>中還看到可以用結構體模擬繼承的方法。代碼如下:

#include <stdio.h>----stdio.h
#include <stdlib.h>----stdlib.h

#define FATHER(child) (struct Father *)(child)

void print1(int i)
{
     printf("this is father and i = %d/n",i);
}

void print2(int i)
{
    printf("this is child and i = %d/n",i);
}

struct Father
{
    int a;

    void (*pointer1_to_function)(int);
};

struct Child
{
    struct Father f;

    int b;

    void (*pointer2_to_function)(int);
};

void father_member_funtion(struct Father *f, char *string)
{
    printf("/n");
    f->pointer1_to_function(f->a);
    printf("%s/n/n",string);
}

int main()
{
    struct Child *p_child;
    struct Father *p_father;
    p_child = (struct Child *)malloc(sizeof(struct Child));
    p_child->f.a = 10;
    p_child->f.pointer1_to_function = print1;

    p_child->b = 20;
    p_child->pointer2_to_function = print2;

    p_child->pointer2_to_function(p_child->b);
    p_father = FATHER(p_child);
    p_father->pointer1_to_function(p_father->a);
    father_member_funtion(p_father,"hello");

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章