我只需要用 C 和 C 语言做一个大型项目,不需要外部库(SDL 除外)。我开始寻找用 C 语言进行某种课程的方法,是什么导致我这样做的:
typedef void (*voidFunction)(void);
typedef struct{
int id;
voidFunction printId;
} Object;
Object *new_Object(int id){
Object *newObject = malloc(sizeof(Object));
newObject->id = id;
void printId(){
static Object *this = NULL;
if(!this) this = newObject;
printf("%d\n", this->id);
};
newObject->printId = printId;
return newObject;
}
int main(){
Object *object = new_Object(5);
object->printId();
object->id++;
object->printId();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
主要输出:
5
6
Run Code Online (Sandbox Code Playgroud)
所以这可行,但是看起来合理吗?如果我在大型项目中使用这种架构,我是否应该预料到会遭到强烈反对?也许我在没有意识到的情况下输入了分配的内存?