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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值