什么是面向对象
为了说明C语言也可以面向对象编程,有必要说一下面向对象中的几个概念:
- 一切事物皆对象
- 对象具有封装和继承特性
- 对象与对象之间使用消息通信,各自存在信息隐藏
可以看出,面向对象只是一种思想,与具体语言无关,只要实现了这几条就是所谓的面向对象了。
看具体代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct _CClass
{
//添加属性
struct _CClass *self; //类本身,相当于C++中的this
int a;
int b;
//添加方法
void (*print)(void *self);
} CParent;
#define EXTERND_CLASS_FROM_CParent \
void (*print)(void *self); \
int a; \
int b; \
typedef struct _CChild
{
//继承CParent
EXTERND_CLASS_FROM_CParent
//添加属性
CParent parent;
int c;
int d;
//添加方法
void (*sayHello)();
} CChild;
void print(void *self);
void sayHello();
int main(int argc, char const *argv[])
{
CParent *parent=(CParent *)malloc(sizeof(CParent));
//为属性赋值
parent->a=1;
parent->b=2;
parent->print=print;
//调用方法
parent->print((void *)parent);
free((void *)parent);
//继承
CChild *child=(CChild *)malloc(sizeof(CChild));
child->a=3;
child->b=5;
child->print=print;
child->sayHello=sayHello;
child->print((void *)child);
child->sayHello();
free((void *)child);
//多态
CChild *child1=(CChild *)malloc(sizeof(CChild));
CParent *parent1=(CParent *)child1;
parent1->a=5;
parent1->b=6;
parent1->print=print;
parent1->print((void *)child1);
free((void *)child1);
return 0;
}
void print(void *self)
{
CParent *tmp=(CParent *)self;
printf("a=%d,b=%d\n",tmp->a,tmp->b);
}
void sayHello()
{
printf("Hello World! \n");
}
原文链接: https://www.cnblogs.com/qinshizhi/archive/2013/04/25/3043492.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/85962
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!