c语言实现c++类,继承,多态的代码完整实现

#include <stdio.h>
//C 语言没有类,但可以用结构体充当一个类
//与类不同,结构体只能定义变量,不能够定义函数,可以通过函数指针的方法来实现其功能 
//定义“类 ”的成员变量以及方法 
typedef struct Person{
    char name;
    int age;
    void (*EatFunction)(struct Person this, int num);
}Person; 
 
//定义函数功能 
void EatFunction(struct Person this, int num){
    printf("Test\n");
} 
 
//定义“类 ”的构造函数
//与面向对象不同,C语言的“类”的 构造函数不能放在“类”中,只能放在“类”外
//构造函数主要完成 变量的初始化,以及函数指针的赋值 
Person *NewPerson(Person *this){
    this->name = 'A';
    this->age = 18;
    this->EatFunction = EatFunction;
} 
 
//主函数调用 
int main(){
    Person person;
    NewPerson(&person);
    person.EatFunction(person,0);
    return 0;
} 
#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;  
  
}  

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值