吃饱了撑的,面向对象程序设计基础就是类,类包括属性和方法,那么结构体中能不能定义函数呢?当然不能!但是可以定义函数指针呀,所以我就想试试看能不能实现一个简单的类。
下面是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语言真的很强大呢。