C++ 设计模式

标签 c++ oop

这样可以吗?我基本上用封装了所有游戏实体和逻辑的类替换了对引用全局变量的单个函数的调用,以下是我想在 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++ 设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10506817/

相关文章:

C++多重继承函数名冲突

javascript - OOP Javascript,从构造函数将单击处理程序附加到按钮无法按预期工作

c++ - g++/clang 覆盖特定函数的链接器

c++ - 如何永久删除主窗口标题栏?

c++ - 如何正确使用 setprecision() 将 ".00"添加到金额的末尾?

oop - 认证授权服务类图

python - `super(...)` 和 `return super(...)` 有什么区别?

php - OOP中的静态函数有什么用?

c++ - 如何阻止 Py_Initialise 使应用程序崩溃?

c++ - C++ 中真的有匿名类/结构吗?