最近一直在想这个问题,我们能用c语言实现c++的核心的几个功能吗?
包括类和接口。
初步的想法是用c语言编译器结合自己写的cxx2c翻译程序实现编译cxx程序的目的.
将原来用cxx写的代码经过cxx2c的翻译程序,将cxx代码中的所有cxx独有的语法翻译成c所能识别的语法规则生成 .c文件,最后用c语言编译器去编译这个文件生成可执行码。
先简单的介绍一下类技术的实现。
(一)类的实现
类的构造和c语言上的结构体是很相似的,甚至有的cxx编译器是将struct和class同等看待的。我们就从struct出发实现类的基本功能。
看如下代码(是用c语言写的,模仿cxx类的一个简单例子):
#include<stdio.h>
struct FClass
{
int age;
char name[20];
void (*printAge)( struct FClass* mythis);//
void (*getName)(struct FClass* mythis);
void (*printName)(struct FClass* mythis);
};
void PrintAge( struct FClass* mythis)
{
printf("%d\n",mythis->age);
}
void GetName(struct FClass* mythis)
{
printf("输入这个人的名字:");
scanf("%s",mythis->name);
}
void PrintName(struct FClass* mythis)
{
printf("%s",mythis->name);
}
int main()
{
struct FClass people={20,"wudeng",PrintAge,GetName,PrintName};
struct FClass people2={21,"zhangsan",PrintAge,GetName,PrintName};
// people.age=20;
// people.p=PrintAge;
people.printAge(&people);
people.getName(&people);
people.printName(&people);
people2.printAge(&people2);
return 1;
}
可以直接运行的。
...................(未完待续)