C语言面向对象编程
2013-06-03 22:43
429 查看
什么是面向对象
为了说明C语言也可以面向对象编程,有必要说一下面向对象中的几个概念:
一切事物皆对象
对象具有封装和继承特性
对象与对象之间使用消息通信,各自存在信息隐藏
可以看出,面向对象只是一种思想,与具体语言无关,只要实现了这几条就是所谓的面向对象了。
看具体代码:
面向对象从来都是思想,而不是语言!
为了说明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"); }
面向对象从来都是思想,而不是语言!
相关文章推荐
- C语言面向对象编程(一):封装与继承
- C语言面向对象编程之二:继承
- C语言面向对象编程[转]
- C语言面向对象编程(四):面向接口编程
- C语言面向对象编程(三):虚函数与多态
- C语言 实现 面向对象编程 OOC
- c语言实现面向对象编程
- 轻量级的C语言面向对象编程框架(约100行代码)
- Objective-C语言介绍 、 Objc与C语言 、 面向对象编程 、 类和对象 、 属性和方法 、 属性和实例变量
- C语言用结构体和指针实现面向对象编程
- C语言面向对象编程之三:虚函数与多态
- C语言面向对象编程(五):单链表实现
- 轻量级的C语言面向对象编程框架
- C语言下的面向对象编程技术
- C语言面向对象编程(五):单链表实现
- 轻量级的C语言面向对象编程框架
- C语言面向对象编程之四:面向接口编程
- C语言 实现 面向对象编程 OOC
- Python源代码 -- C语言实现面向对象编程(基类&派生类&多态)
- 用C语言模拟面向对象编程(转)