C语言实现面向对象的一种方式

从某天开始,我认为面向对象只是一种思想,至于用什么语言实现,怎么实现,其实就看语言的开发者怎么去思考这种问题。以下代码是我用纯C语言实现面向对象的一种方式。C语言实现面向对象从应用级开发来讲,纯粹是个鸡肋,所以勿喷!这里只是提供一个思考问题的方向而已!

先来一个父类的头文件 Father.h

#ifndef _FATHER_H_
#define _FATHER_H_

typedef int(*PrintInfo)();

#define CLASS_BASE()    \
int nValue;             \
PrintInfo Fun_Print;


#ifdef __cplusplus
extern "C"
{
#endif

	struct S_BASE
	{
		CLASS_BASE()
	};

	int Base_Init(struct S_BASE* pBase);
	int Base_Print();

#ifdef __cplusplus
}
#endif

#endif // !_FATHER_H_

再来一个父类的方法(函数)实现 Father.c

#include "Father.h"
#include <stdio.h>

int Base_Init(struct S_BASE* pBase)
{
	pBase->nValue = 0;
	pBase->Fun_Print = &Base_Print;
	return 0;
}

int Base_Print()
{
	printf("I am Base\n");
	return 0;
}

好啦,来两个子类,Son.h

#ifndef _SON_H_
#define _SON_H_
#include "Father.h"
#ifdef __cplusplus
extern "C"
{
#endif
	struct S_SON_A
	{
		CLASS_BASE()
		char chData;
	};

	struct S_SON_B
	{
		CLASS_BASE()
		float fData;
	};

	int Init_SON_A(struct S_SON_A* pSon);
	int Init_SON_B(struct S_SON_B* pSon);
	int Son_Print();

#ifdef __cplusplus
}
#endif
#endif // !_SON_H_

子类的实现Son.c

#include "Son.h"
#include <stdio.h>

int Init_SON_A(struct S_SON_A* pSon)
{
	Base_Init((struct S_BASE*)pSon);
	pSon->nValue = 1;
	pSon->chData = 'A';
	return 0;
}

int Init_SON_B(struct S_SON_B* pSon)
{
	Base_Init((struct S_BASE*)pSon);
	pSon->Fun_Print = &Son_Print;
	pSon->fData = 1.0;
	return 0;
}

int Son_Print()
{
	printf("I am Son!\n");
	return 0;
}

好啦,最后测试一下main.c

#include <stdio.h>
#include "Son.h"

int main()
{
	struct S_BASE* pBase;
	struct S_SON_A Son_A;
	struct S_SON_B Son_B;

	Init_SON_A(&Son_A);
	Init_SON_B(&Son_B);

	pBase = &Son_A;
	pBase->Fun_Print();

	pBase = &Son_B;
	pBase->Fun_Print();
	getchar();
	return 0;
}

至于结果,那就不详细说了!

面向对象的三大特性,封装、继承和多态!个人认为,实现多态才是将面向对象这个思想发挥到一定的高度,上面的代码,实际上就是将多态用C语言实现了一遍!


版权声明:本文为zhou865612640原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。