Is it possible to subclass a C struct in C++ and use pointers to the struct in C code?

后端 未结 10 1071
滥情空心
滥情空心 2021-02-07 00:10

Is there a side effect in doing this:

C code:

struct foo {
      int k;
};

int ret_foo(const struct foo* f){ 
    return f.k; 
}

C++ c

10条回答
  •  走了就别回头了
    2021-02-07 00:48

    This is perfectly legal, though it might be confusing for other programmers.

    You can use inheritance to extend C-structs with methods and constructors.

    Sample :

    struct POINT { int x, y; }
    class CPoint : POINT
    {
    public:
        CPoint( int x_, int y_ ) { x = x_; y = y_; }
    
        const CPoint& operator+=( const POINT& op2 )
        { x += op2.x; y += op2.y; return *this; }
    
        // etc.
    };
    

    Extending structs might be "more" evil, but is not something you are forbidden to do.

提交回复
热议问题