c++ - 仅使用 C 结构并保持 OOPy?

标签 c++ c function-pointers struct pointer-to-member

假设你有:

struct c_struct {
   int value;
   /* other stuff */
   void (* dump)();
};

并且您希望在某个时候:

c_struct_obj->dump();

我认为你无法实例化一个 c_struct 对象,使其特定的“dump”函数知道其特定的“值”,就像 C++ 方法知道成员变量的方式(我想是通过隐式的“this”)?我想我已经知道答案了(“不”)。如果是这样,是否还有其他方式以 OOPy 方式使用 C 结构体?

最佳答案

当然,您只需自己传递this即可:

struct c_struct {
    int value;
    /* other stuff */
    void (* dump)(struct c_struct *this);
};

然后用以下方式调用它:

c_struct_obj->dump(c_struct_obj);

关于c++ - 仅使用 C 结构并保持 OOPy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971554/

相关文章:

c++ - 测量分布式应用程序的内存使用情况

c++ - 两点交叉操作

c++ - 检测 Windows 在崩溃或电源故障后何时重新启动

c - gtk 3 新应用程序使用旧命令行参数

c - pthread_create(...) 执行函数 - 指针混淆

C 指针数组的 int 比较器

c++ - 使用线程对数组的两半进行排序,但仅对后半部分进行排序

c - 如何在 "object oriented"C中动态初始化数组?

c - 在递归中使用 realloc

c++ - 来自类型 <未解析的重载函数类型> 的无效 static_cast