您的位置:首页 > 编程语言 > C语言/C++

C语言面向对象的思想(实现继承和多态)

2013-03-04 23:05 661 查看
由于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;


3. 多态

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

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

我们使用上面定义的两个结构体Parent, 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;

/*Use parent pointer to point to child*/
q = (Parent *)p;
/*Be attention!*/
/*Actually the child's print function is called!*/
q->print(q);

destroy_child(&p);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: