开发者

Pure C that mimics object-oriented programming? [duplicate]

This question already has answers here: 开发者_运维问答 Closed 12 years ago.

Possible Duplicates:

Object oriented programming in C

Can you write object oriented code in C?

Hi

I know there are some coding styles for pure C that mimics object-oriented programming : "method call"(functions) on "objects"(struct) .c and .h organisation, and so on...

What are your habits about that ?

Is there some good tutorial on that ? Or examples ?


You should definitively have a look at the GTK+ Project Deriving, using events, hierarchies of widgets, through the big amount of code you'll get a good impression on how OO in C can look like. There is even a quite good implementation of Reflexion (which other programming frameworks like Java or .NET have more or less built-in) called "introspection".

Gtk+ is definively a very good example of object oriented programming in C.


One common approach is to design a header file that forward-declares a struct, then defines a number of functions that take a pointer to that struct as a "this" pointer. For example:

struct vector; // Forward-declaration; no implementation shown.

struct vector* VectorNew(/* ... */);
void VectorAppend(struct vector* this, void* toAppend);
size_t VectorSize(const struct vector* this);

Then, in the .c file, you can actually provide the full struct definition and the associated function definitions. This prevents clients from reading the raw fields, since they're only in the .c file, and gives a sort of "namespace" to the "member functions" by using a consistent prefix.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜