首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >[ANSI-C]像类一样使用结构

[ANSI-C]像类一样使用结构
EN

Stack Overflow用户
提问于 2012-08-17 15:05:23
回答 1查看 225关注 0票数 2

我正在为嵌入式设备开发“第一个”C软件。

我想用oo风格编写代码,所以我开始使用structs。

代码语言:javascript
复制
typedef struct sDrawable {
    Dimension size;
    Point location;
    struct sDrawable* parent;
    bool repaint;
    bool focused;
    paintFunc paint;
} Drawable;

typedef struct sPanel {
    Drawable drw;
    struct sDrawable* child;
    uint16_t bgColor;
} Panel;

我不能也不想使用malloc,所以我搜索更好的方法来实例化我的结构。这可以接受吗?

代码语言:javascript
复制
Panel aPanel={0};

void Gui_newPanel(Panel* obj, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t bgColor) {
    // Drw is a macro to cast to (Drawable*)
    Drw(obj)->repaint = true;
    Drw(obj)->parent= NULL;
    Drw(obj)->paint = (paintFunc) &paintPanel;
    Drw(obj)->location=(Point){x, y};
    Drw(obj)->size=(Dimensione){w, h};
    obj->child = NULL;
    obj->bgColor = bgColor;
}

void Gui_init(){
    Gui_newPanel(&aPanel, 0, 0, 100, 100, RED);
}

更新

在第一种情况下,我必须像Panel aPanel={0};一样初始化结构,以传递指向Gui_newPanel函数的指针,还是只能编写Panel aPanel;?我测试过两种方法,但也许我只是运气不好.

或者这是个更好的方法?

代码语言:javascript
复制
Panel aPanel;

Panel Gui_newPanel(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t bgColor) {
    // Drw is a macro to cast to (Drawable*)
    Panel obj;
    Drw(&obj)->repaint = true;
    Drw(&obj)->parent= NULL;
    Drw(&obj)->paint = (paintFunc) &paintPanel;
    Drw(&obj)->location = (Point){x, y};
    Drw(&obj)->size = (Dimension){w, h};
    obj.child = NULL;
    obj.bgColor = bgColor;
    return obj;
}

void Gui_init(){
    aPanel=Gui_newPanel(0, 0, 100, 100, RED);
}

这些方法中哪一种更可取?

我对性能和内存使用特别感兴趣。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-17 15:15:56

按值返回struct可能会导致复制结构成员的开销,尽管编译器通常会很聪明地对其进行优化。如果您关心开销,您应该分析这两种方法的相对性能。

此外,检查设备的目标编译器是否实际上能够支持返回的结构-一些非常老的编译器不支持返回或分配结构。

如果您有一个合理的现代编译器,您可能能够直接返回一个struct文本,这将是有效的:

代码语言:javascript
复制
return (Panel) {
    .drw = {
        .size = {w, h},
        .location = {x, y},
        // ...
    },
    .child = NULL,
    .bgColor = bgColor
};
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12008336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档