C语言实现面向对象(封装、继承、多态)

#include <stdio.h>
#include <stdlib.h>
 
typedef void (*FUNC_TYPE)(void *); 

//虚函数表结构
struct vtbl
{
	FUNC_TYPE dance;
	FUNC_TYPE jump;
};

//基类
struct base
{
    /*virtual table*/
	struct vtbl *vptr;
	FUNC_TYPE dance;
	FUNC_TYPE jump;
};
void dance(void *vPtr)
{
	struct base * b = (struct base *)vPtr;
	b->vptr->dance(vPtr);
}
void jump(void *vPtr)
{
	struct base * b = (struct base *)vPtr;
	b->vptr->jump(vPtr);
}

void base_dance(void *this)
{
	printf("base dance\n");
}
 
void base_jump(void *this)
{
	printf("base jump\n");
}
 
/* global vtable for base */
struct vtbl base_table =
{
		base_dance,
		base_jump
};

void ConstructBase(void * vPtr)
{
	struct base * this = (struct base *)vPtr;
	this->vptr = &base_table;
	this->dance = dance;
	this->jump = jump;
	return ;
}

//基类的构造函数
struct base * new_base()
{
    struct base *temp = (struct base *)malloc(sizeof(struct base));
	temp->vptr = &base_table;
	temp->dance = dance;
	return temp;
}
 
//派生类
struct Derived
{
	struct base m_base;
	/*derived members */
	int high;
};
 
void derived_dance(void * this)
{
	/*implementation of derived's dance function */
	printf("derived dance\n");
}
 
void derived_jump(void * this)
{
	/*implementation of Derived's jump function */
	struct Derived* temp = (struct Derived *)this;
	printf("Derived jump:%d\n", temp->high);
}
 
/*global vtable for Derived */
struct vtbl Derived_table =
{
	&derived_dance,
	&derived_jump
};

void ConstructDerived(void * vPtr)
{
	struct Derived * this = (struct Derived *)vPtr;
	this->m_base.vptr = &Derived_table;
	this->m_base.dance = dance;
	this->m_base.jump = jump;
	return ;
}
//派生类的构造函数
struct Derived * new_derived(int h)
{
    struct Derived * this= (struct Derived *)malloc(sizeof(struct Derived));
	this->m_base.vptr = &Derived_table;
	this->m_base.dance = dance;
	this->m_base.jump = jump;
	this->high = h;
	return this;
}
int main(void)
{

    struct base * bas = new_base();
    //这里调用的是基类的成员函数
    bas->vptr->dance((void *)bas);
    bas->vptr->jump((void *)bas);
    
    struct Derived * child = new_derived(100);
    //基类指针指向派生类
    bas  = (struct base *)child;
 
    //这里调用的其实是派生类的成员函数
    bas->vptr->dance((void *)bas);
    bas->vptr->jump((void *)bas);
    
 	bas->dance((void *)bas);
 	bas->jump((void *)bas);

//-----------------------------------------------
 	struct base Base2;
 	ConstructBase(&Base2);
 	Base2.dance(&Base2);
 	Base2.jump(&Base2);

	return 0;
}

运行结果:
base dance
base jump
derived dance
Derived jump:100
derived dance
Derived jump:100
base dance
base jump

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值