C作为一种面向对象的语言 [英] C as an object oriented language

查看:111
本文介绍了C作为一种面向对象的语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以建议的C语言使用它以类似的方式不是一个面向对象的语言语法?我知道,他们不可能是相同的,某些关键字不是在C present,但我不知道是否有利用的某些方面(如继承)甚至在C程序的方法。

Could you suggest a syntax for the C language to use it in a similar way than an object-oriented language? I know that they cannot be the same and that some keywords aren't present in C, but I'm wondering if there is a way to take advantage of certain aspects (like inheritance) even in a C program.

推荐答案

您可以实现多态性与普通函数和虚拟表(虚函数表)。下面是我发明的(基于C ++)进行编程锻炼pretty整齐系统:

You can implement polymorphism with regular functions and virtual tables (vtables). Here's a pretty neat system that I invented (based on C++) for a programming exercise:

的构造分配内存,然后调用类的',其中的内存初始化初始化函数。每个初始化函数还应该包含包含虚拟函数指针(NULL纯虚拟的)一个静态的虚函数表结构。派生类初始化函数做其他事情之前调用父类init函数。

The constructors allocate memory and then call the class' init function where the memory is initialized. Each init function should also contain a static vtable struct that contains the virtual function pointers (NULL for pure virtual). Derived class init functions call the superclass init function before doing anything else.

有一个非常漂亮的API,可以通过实现虚拟函数封装创建(不要与功能相混淆指向的虚函数表)如下(请将静态内联中它的面前,如果你这样做在标题中):

A very nice API can be created by implementing the virtual function wrappers (not to be confused with the functions pointed to by the vtables) as follows (add static inline in front of it, if you do this in the header):

int playerGuess(Player* this) { return this->vtable->guess(this); }

单继承可以滥用一个结构的二进制布局来完成:

Single inheritance can be done by abusing the binary layout of a struct:

请注意,多重继承是混乱的,你经常需要调整类型层次间铸造,当指针值。

Notice that multiple inheritance is messier as then you often need to adjust the pointer value when casting between types of the hierarchy.

其它类型特定的数据可以被添加到该虚拟表为好。例子包括运行时类型信息(例如,类型名称作为字符串),连接进行超虚函数表和析构函数链。你可能需要虚析构函数,其中派生类的析构函数的降级对象到它的超类,然后递归地调用的析构函数等,直至达到基类的析构函数,并终于释放结构。

Other type-specific data can be added to the virtual tables as well. Examples include runtime type info (e.g. type name as a string), linking to superclass vtable and the destructor chain. You probably want virtual destructors where derived class destructor demotes the object to its super class and then recursively calls the destructor of that and so on, until the base class destructor is reached and that finally frees the struct.

这篇关于C作为一种面向对象的语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆