Object-orientation in C

前端 未结 22 1755
孤城傲影
孤城傲影 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:13

    #include "triangle.h"
    #include "rectangle.h"
    #include "polygon.h"
    
    #include 
    
    int main()
    {
        Triangle tr1= CTriangle->new();
        Rectangle rc1= CRectangle->new();
    
        tr1->width= rc1->width= 3.2;
        tr1->height= rc1->height= 4.1;
    
        CPolygon->printArea((Polygon)tr1);
    
        printf("\n");
    
        CPolygon->printArea((Polygon)rc1);
    }
    

    Output:

    6.56
    13.12
    

    Here is a show of what is OO programming with C.

    This is real, pure C, no preprocessor macros. We have inheritance, polymorphism and data encapsulation (including data private to classes or objects). There is no chance for protected qualifier equivalent, that is, private data is private down the innheritance chain too. But this is not an inconvenience because I don't think it is necessary.

    CPolygon is not instantiated because we only use it to manipulate objects of down the innheritance chain that have common aspects but different implementation of them (Polymorphism).

提交回复
热议问题