C++ 设计模式

c++ design pattern

本文关键字:设计模式 C++      更新时间:2023-10-16

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

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;
}

拥有一个包含游戏/事件/...循环,执行此类操作的常用方法是使用构造函数来设置对象,然后提供一个单独的方法来开始冗长的阐述。

像这样:

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框架:

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

我不是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;
}
构造

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