C语言面向对象的模拟(1)
来源:互联网 发布:神雕侠侣 gotv 源码 编辑:程序博客网 时间:2024/06/05 04:53
吃饱了撑的,面向对象程序设计基础就是类,类包括属性和方法,那么结构体中能不能定义函数呢?当然不能!但是可以定义函数指针呀,所以我就想试试看能不能实现一个简单的类。
下面是Car类型的定义:car.h
/*car.h--car类型头文件*/
#ifndef CAR_H_
#define CAR_H_
/*类型定义*/
typedef struct car
{
int wheels;
void (*hello)(int);
void (*setwheels)(int *,int);
}Car;
/*Car类型的方法声明*/
void f_hello(int wheels);
void f_setwheels(int * carwheels,int wheels);
#endif
Car类型方法的实现:car.c
/*car.c--Car类型方法的实现*/
#include<stdio.h>
void f_hello(int wheels)
{
printf("I have %d wheels.\n",wheels);
}
void f_setwheels(int * carwheels,int wheels)
{
*carwheels = wheels;
}
简单测试:struct_fun.c
/*struct_fun.c--结构体中定义函数指针,面向对象测试*/
#include<stdio.h>
#include"car.h"
int main(void)
{
/*对象初始化,属性和方法初始化*/
Car car1;
car1.wheels = 4;
car1.hello = &f_hello;
car1.setwheels = &f_setwheels;
/*car方法测试*/
car1.hello(car1.wheels);
car1.setwheels(&car1.wheels,5);
car1.hello(car1.wheels);
return 0;
}
测试结果:
I have 4 wheels.
I have 5 wheels.
是不是有面向对象的范儿呢?C语言真的很强大呢。
- C语言面向对象的模拟(1)
- 用C语言模拟面向对象编程
- 用C语言模拟面向对象
- 用C语言模拟面向对象
- 用C语言模拟面向对象
- C语言中的面向对象(1)-类模拟和多态,继承(转载)
- C语言的面向对象
- 面向对象的c语言
- 老码识途 创造面向对象语言(使用C模拟C++)
- C模拟面向对象的方法
- 用C语言模拟面向对象编程(转)
- 用C语言模拟面向对象编程(上)
- 用C语言模拟面向对象编程(上)
- C语言中的面向对象-类模拟的性能分析
- C语言中的面向对象(1)-类模拟和多态,继承
- C语言面向对象
- C语言面向对象
- 面向对象的C语言(OOPC)之按键
- maven插件
- 我们工作到底为了什么?(这篇文章很重要,强烈推荐)
- SDUTOJ 1525 字符统计2
- Hibertemplate
- 局域网IPC入侵心得
- C语言面向对象的模拟(1)
- JS获取事件源的位置
- Ajax的一个疑问
- SQLite不支持的SQL语法总结
- wget 编译方法
- sqlite3 常用操作
- 关于JS函数parseInt()说明
- SQLite中的空处理的比较
- 建立系统项目