c 封装c语言程序,C语言实现封装、继承和多态

1. 封装

c语言中虽然没有类,但有struct和指针。我们可以在一个struct中存入数据和函数指针,以此来模拟类行为。

typedef struct _parent

{

int a;

int b;

void (*print)(struct _parent *this);

}parent;

封装性的意义在于,函数和数据是绑在一起的,数据和数据是绑在一起的。这样,我们就可以通过简单的一个结构指针访问到所有的数据,遍历所有的函数。封装性,这是类拥有的属性,当然也是数据结构体拥有的属性。

2.继承

如果要完全地用c语言实现继承,可能有点难度。但如果只是简单的做一下,保证子类中含有父类中的所有成员。这还是不难的。

typedef struct _child

{

parent parent;

int c;

}child;

在设计c语言继承性的时候,我们需要做的就是把基础数据放在继承的结构的首位置即可。这样,不管是数据的访问、数据的强转、数据的访问都不会有什么问题。

3. 多态

这个特性恐怕是面向对象思想里面最有用的了。

要用c语言实现这个特性需要一点点技巧,但也不是不可能的。

我们使用上面定义的两个结构体parent, child。简单地描述了一个多态的例子。

#include

#include

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值