C as an object oriented language

前端 未结 5 2202
闹比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:08

    The traditional solution is the function pointer struct. I emphasize traditional. I can tell you what sort of code I wrote in PL/I and C years ago, but I don't claim to speak for the state of the 'art' if you can call this art.

    There are many variations on this, and the below is a bit of a compromise.

    struct SortOfAnAbstractClass {
       int (*function1)(SortOfAnAbstractClass* this, int arg1, int arg2, char * arg3);
       void (*function2)(SortOfAnAbstractClass* this, char *arg);
    };
    
    struct SortOfDerived {
       struct SortOfAnAbstractClass base;
       int instanceVariable1;
    };
    
    SortOfAnAbstractClass getMeOne() {
         SortOfDerived *d = malloc(sizeof SortOfDerived);
         memset(d, 0, sizeof SortOfDerived);
         d->function1 = myf1;
         d->function2 = myf2;
         return &d->base;
    };
    

    and then 'myf1' and 'myf2' cast their 'this' parameters and go to town. You can extend this to look ever more like a full virtual dispatch.

    Another common variation from the mists of time:

    struct SortOfAClass {
       void *creatorInfo;
       int (*function1)(SortOfAnAbstractClass* this, int arg1, int arg2, char * arg3);
       void (*function2)(SortOfAnAbstractClass* this, char *arg);
    };
    

    In this variation, there's no inheritance by inclusion. The derived classes each put their private state into their own object in creatorInfo.

提交回复
热议问题