c ++设计模式

coo*_*roc 0 c++ oop

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

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;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*lia 9

拥有包含game/events/...循环的构造函数并不常见,通常的方法是使用构造函数来设置对象,然后提供一个单独的方法来启动冗长的细化.

像这样的东西:

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;
}
Run Code Online (Sandbox Code Playgroud)

实际上,几乎任何GUI框架都提供了一个"应用程序"对象,其行为就像那样; 以Qt框架为例:

int main(...)
{
    QApplication app(...);
    // ... perform other initialization tasks ...
    return app.exec(); // starts the event loop, typically returns only at the end of the execution
}
Run Code Online (Sandbox Code Playgroud)


dre*_*lax 7

我不是C++大师,但我可能会这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

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