首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++设计模式

c++设计模式
EN

Stack Overflow用户
提问于 2012-05-09 05:31:30
回答 2查看 142关注 0票数 0

这样可以吗?我基本上用封装了所有游戏实体和逻辑的类替换了对引用全局变量的单个函数的调用,下面是我想在main中调用新类的方式,我只是想知道c++大师对此的共识是什么。

代码语言:javascript
复制
class thingy
{
public:
    thingy()
    {
        loop();
    }
    void loop()
    {
        while(true)
        {
            //do stuff

            //if (something)
                //break out
        }
    }
};

int main (int argc, char * const argv[]) 
{
    thingy();
    return 0;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-09 05:34:17

包含游戏/事件/...的构造函数并不常见。循环中,通常这样做的方法是使用构造函数来设置对象,然后提供一个单独的方法来开始冗长的细化。

如下所示:

代码语言:javascript
复制
class thingy
{
public:
    thingy()
    {
        // setup the class in a coherent state
    }

    void loop()
    {
        // ...
    }
};

int main (int argc, char * const argv[]) 
{
    thingy theThingy;
    // the main has the opportunity to do something else
    // between the instantiation and the loop
    ...
    theThingy.loop();
    return 0;
}

实际上,几乎所有的GUI框架都提供了一个“应用程序”对象,它的行为就像这样;例如Qt框架:

代码语言:javascript
复制
int main(...)
{
    QApplication app(...);
    // ... perform other initialization tasks ...
    return app.exec(); // starts the event loop, typically returns only at the end of the execution
}
票数 9
EN

Stack Overflow用户

发布于 2012-05-09 05:37:23

我不是C++专家,但我可能会这样做:

代码语言:javascript
复制
struct thingy
{
    thingy()
    {
        // set up resources etc
    }

    ~thingy()
    {
        // free up resources
    }

    void loop()
    {
        // do the work here
    }
};

int main(int argc, char *argv[])
{
    thingy thing;
    thing.loop();
    return 0;
}

构造函数是用来构造对象的,而不是用来处理整个应用程序逻辑的。同样,如果需要,在构造函数中获取的任何资源都应该在析构函数中进行适当的处理。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10506817

复制
相关文章

相似问题

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