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

后端 未结 10 1049
滥情空心
滥情空心 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:47

    I certainly not recommend using such weird subclassing. It would be better to change your design to use composition instead of inheritance. Just make one member

    foo* m_pfoo;

    in the bar class and it will do the same job.

    Other thing you can do is to make one more class FooWrapper, containing the structure in itself with the corresponding getter method. Then you can subclass the wrapper. This way the problem with the virtual destructor is gone.

提交回复
热议问题