C as an object oriented language

前端 未结 5 2200
闹比i
闹比i 2020-12-29 12:37

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

5条回答
  •  鱼传尺愫
    2020-12-29 13:07

    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:
    (source: goblin.tkk.fi)

    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.

    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:
    (source: goblin.tkk.fi)

    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.

提交回复
热议问题