这样可以吗?我基本上用封装了所有游戏实体和逻辑的类替换了对引用全局变量的单个函数的调用,以下是我想在 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/