Can you write object-oriented code in C? [closed]

2018-12-31 02:16发布

Can you write object-oriented code in C? Especially with regard to polymorphism.


See also Stack Overflow question Object-orientation in C.

标签: c oop object
30条回答
永恒的永恒
2楼-- · 2018-12-31 02:36

Which articles or books are good to use OOP concepts in C?

Dave Hanson's C Interfaces and Implementations is excellent on encapsulation and naming and very good on use of function pointers. Dave does not try to simulate inheritance.

查看更多
浪荡孟婆
3楼-- · 2018-12-31 02:38

If you are convinced that an OOP approach is superior for the problem you are trying to solve, why would you be trying to solve it with a non-OOP language? It seems like you're using the wrong tool for the job. Use C++ or some other object-oriented C variant language.

If you are asking because you are starting to code on an already existing large project written in C, then you shouldn't try to force your own (or anyone else's) OOP paradigms into the project's infrastructure. Follow the guidelines that are already present in the project. In general, clean APIs and isolated libraries and modules will go a long way towards having a clean OOP-ish design.

If, after all this, you really are set on doing OOP C, read this (PDF).

查看更多
初与友歌
4楼-- · 2018-12-31 02:41

Of course, it just won't be as pretty as using a language with built-in support. I've even written "object-oriented assembler".

查看更多
唯独是你
5楼-- · 2018-12-31 02:42

Yes, but I have never seen anyone attempt to implement any sort of polymorphism with C.

查看更多
浮光初槿花落
6楼-- · 2018-12-31 02:43

You may find it helpful to look at Apple's documentation for its Core Foundation set of APIs. It is a pure C API, but many of the types are bridged to Objective-C object equivalents.

You may also find it helpful to look at the design of Objective-C itself. It's a bit different from C++ in that the object system is defined in terms of C functions, e.g. objc_msg_send to call a method on an object. The compiler translates the square bracket syntax into those function calls, so you don't have to know it, but considering your question you may find it useful to learn how it works under the hood.

查看更多
与君花间醉酒
7楼-- · 2018-12-31 02:43

A little OOC code to add:

#include <stdio.h>

struct Node {
    int somevar;
};

void print() {
    printf("Hello from an object-oriented C method!");
};

struct Tree {
    struct Node * NIL;
    void (*FPprint)(void);
    struct Node *root;
    struct Node NIL_t;
} TreeA = {&TreeA.NIL_t,print};

int main()
{
    struct Tree TreeB;
    TreeB = TreeA;
    TreeB.FPprint();
    return 0;
}
查看更多
登录 后发表回答