C语言如何实现封装继承和多态

1. 封装

成员变量比较好说,关键是成员函数怎么办?C中的结构体如何放一个成员函数呢?
答:可以使用函数指针。

typedef struct Base
{
	int a;
	void (*print)(struct Base* this);
}Base;
//模仿基类构造
Base* baseCtor(int a) {
	Base* this = (Base*)malloc(sizeof(Base));
	if(this){
		this->a = a;
		this->print = printBase;//基类的打印函数
	}
	return this;
}
//模仿基类析构
void baseDtor(Base** p){
	if(*p){
		free(*p);
		*p = NULL;
	}
}

void printBase(Base* this){
	printf("Base contains: %d\n", this->a);
}

2. 继承

继承只好通过内嵌一个其他结构体的实例实现。

typedef struct Derived
{
	Base mbase;
	int b;
}Derived;
//模仿派生类构造
Derived* derivedCtor(int a, int b){
	Derived* this = (Derived*)malloc(sizeof(Derived));
	if(this){
		this->mbase.a = a;
		this->b = b;
		this->mbase.print = printDerived;//派生类的打印函数
	}
	return this;
}
//模仿派生类析构
void derivedDtor(Derived** p){
	if(*p){
		free(*p);
		*p = NULL;
	}
}

void printDerived(Base* this){
	Derived* pderived = (Derived*)this;
	printf("Derived contains: %d %d\n", pderived->mbase.a, pderived->b);
}

3. 多态

怎么实现多态?需要利用结构体中的函数指针。
如何利用?构造时将其指向不同的函数。
以下是全部代码:

#include <stdio.h>
#include <malloc.h>

typedef struct Base
{
	int a;
	void (*print)(struct Base* this);
}Base;

typedef struct Derived
{
	Base mbase;
	int b;
}Derived;

void printBase(Base* this){
	printf("Base contains: %d\n", this->a);
}

void printDerived(Base* this){
	Derived* pderived = (Derived*)this;
	printf("Derived contains: %d %d\n", pderived->mbase.a, pderived->b);
}

Base* baseCtor(int a) {
	Base* this = (Base*)malloc(sizeof(Base));
	if(this){
		this->a = a;
		this->print = printBase;
	}
	return this;
}
void baseDtor(Base** p){
	if(*p){
		free(*p);
		*p = NULL;
	}
}

Derived* derivedCtor(int a, int b){
	Derived* this = (Derived*)malloc(sizeof(Derived));
	if(this){
		this->mbase.a = a;
		this->b = b;
		this->mbase.print = printDerived;
	}
	return this;
}
void derivedDtor(Derived** p){
	if(*p){
		free(*p);
		*p = NULL;
	}
}

int main(int argc, char* argv[]) 
{
	Derived* pd = derivedCtor(1,2);
	Base* pb = (Base*)pd;//基类指针指向派生类对象
	pb->print(pb);//调用的是派生类的打印函数
	derivedDtor(&pd);
	return 0; 
} 

输出:
在这里插入图片描述

4. 总结

  • 封装:结构体内放入函数指针;
  • 继承:结构体内嵌别的结构体;
  • 多态:函数指针指向不同的函数。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值