Object-orientation in C

前端 未结 22 1773
孤城傲影
孤城傲影 2020-11-22 15:26

What would be a set of nifty preprocessor hacks (ANSI C89/ISO C90 compatible) which enable some kind of ugly (but usable) object-orientation in C?

I am familiar with

22条回答
  •  时光说笑
    2020-11-22 16:07

    I once worked with a C library that was implemented in a way that struck me as quite elegant. They had written, in C, a way to define objects, then inherit from them so that they were as extensible as a C++ object. The basic idea was this:

    • Each object had its own file
    • Public functions and variables are defined in the .h file for an object
    • Private variables and functions were only located in the .c file
    • To "inherit" a new struct is created with the first member of the struct being the object to inherit from

    Inheriting is difficult to describe, but basically it was this:

    struct vehicle {
       int power;
       int weight;
    }
    

    Then in another file:

    struct van {
       struct vehicle base;
       int cubic_size;
    }
    

    Then you could have a van created in memory, and being used by code that only knew about vehicles:

    struct van my_van;
    struct vehicle *something = &my_van;
    vehicle_function( something );
    

    It worked beautifully, and the .h files defined exactly what you should be able to do with each object.

提交回复
热议问题