c语言实现的多态

print.h

#ifndef __PRINT_H__
#define __PRINT_H__

typedef void (*print_fn) (void *print_info, char *str);

struct print_info
{
    print_fn print;
};

#endif

bird.c

#include "bird.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void bird_fly(struct bird *xBird)
{
    printf("bird %s fly\r\n",xBird->name);
}
void print_bird(struct bird *xBird, char *str) {
    printf("bird name=%s,str = %s\r\n", xBird->name,str);
}

static const struct print_info print_interface = {
    .print = (print_fn)print_bird,
};

struct bird * init_bird(char *name)
{
    struct bird *bird = malloc(sizeof(struct bird));
    bird->name = name;
    bird->interface = &print_interface;
    bird->fly = (bird_fly_fn)bird_fly;
    return bird;
}

void free_bird(struct bird *xBird)
{
    free(xBird);
}

bird.h

#ifndef __BIRD_H__
#define __BIRD_H__

#include "print.h"

typedef void (*bird_fly_fn)(void);

struct bird {
    const struct print_info *interface;
    bird_fly_fn fly;
    char *name;
};

struct bird * init_bird(char *name);
void free_bird(struct bird *xBird);


#endif

dog.c

#include <stdio.h>
#include "dog.h"
#include <string.h>
#include <stdlib.h>

void run_dog(struct dog *xDog) {
    printf("dog %s run\r\n",xDog->name);
}

void print_dog(struct dog *xDog, char *str) {
    printf("dog name=%s,str = %s\r\n", xDog->name,str);
}

static const struct print_info print_interface= {
    .print = (print_fn)print_dog,
};

struct dog * init_dog(char *name) {
    struct dog *xDog = malloc(sizeof(struct dog));
    xDog->name = name;
    xDog->interface = &print_interface;
    xDog->run = (dog_run_fn)run_dog;

    return xDog;
}

void free_dog(struct dog *xDog) {
    free(xDog);
}

dog.h

#ifndef __DOG_H__
#define __DOG_H__

#include "print.h"

typedef void (*dog_run_fn) (void *dog);

struct dog {
    const struct print_info *interface;
    dog_run_fn run;
    char *name;
};

struct dog * init_dog(char *name);
void free_dog(struct dog *xDog);

#endif

main.c

#include <stdio.h>
#include <stdlib.h>
#include "dog.h"
#include "bird.h"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

	struct dog *dog1;
	struct bird *bird1;
	struct print_info **p;

	dog1 = init_dog("Keji");
	p = (struct print_info **)dog1;
	(*p)->print(dog1,"dog1");

	bird1 = init_bird("King");
	p = (struct print_info **)bird1;
	(*p)->print(bird1,"bird1");


	free_dog(dog1);
	free_bird(bird1);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值