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;
}