如何将包含构造函数的 C++ 类转换为 C 结构?

ken*_*enn -1 c c++

我想在C的窗口中绘制矩形。我找到了以下C++ 代码, 我想将其类转换为C结构以在我的C项目中使用它。我想将以下C++类转换为C结构:

class Rect{
public:
    int x1;
    int y1;
    int x2;
    int y2;
    Rect * next;

    Rect(){
        x1 = y1 = x2 = y2 = 0;
        next = NULL;
    }

    void draw(Display* d, Window w, GC gc){
        if((x1<x2) && (y1<y2)){
            XDrawRectangle(d, w, gc, x1, y1, x2-x1, y2-y1);
        }
        if((x1<x2) && (y1>y2)){
            XDrawRectangle(d, w, gc, x1, y2, x2-x1, y1-y2);
        }
        if((x1>x2) && (y1>y2)){
            XDrawRectangle(d, w, gc, x2, y2, x1-x2, y1-y2);
        }
        if((x1>x2) && (y1<y2)){
            XDrawRectangle(d, w, gc, x2, y1, x1-x2, y2-y1);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

我看到可以在此处此处将某些C++类转换为C结构,但上述类包含构造函数。如何将包含构造函数的类转换为C结构并安全使用它?

All*_*ind 6

您创建一个包含方法的数据和函数的结构:

struct Rect {
   int x1;
   int y1;
   int x2;
   int y2;
   struct Rect *next;
};

struct Rect *Rect_init(struct Rect *r) {
    assert(r);
    r->x1 = 0;
    r->y1 = 0;
    r->x2 = 0;
    r->y2 = 0;
    r->next = 0;
    return r;
}

void Rect_draw(struct Rect *r, Window w, GC gc) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

大多数 c 程序员可能只是初始化值而不是编写 Rect_init() 函数:

struct Rect r = { 0 };
Run Code Online (Sandbox Code Playgroud)

  • 您可以对结构进行“typedef”以避免所有不必要的“struct”关键字:https://wandbox.org/permlink/KsUzNLFWZm4fDldI (2认同)