这样可以吗?我基本上用封装了所有游戏实体和逻辑的类替换了对引用全局变量的单个函数的调用,下面是我想在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;
}发布于 2012-05-09 05:34:17
包含游戏/事件/...的构造函数并不常见。循环中,通常这样做的方法是使用构造函数来设置对象,然后提供一个单独的方法来开始冗长的细化。
如下所示:
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
}发布于 2012-05-09 05:37:23
我不是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;
}构造函数是用来构造对象的,而不是用来处理整个应用程序逻辑的。同样,如果需要,在构造函数中获取的任何资源都应该在析构函数中进行适当的处理。
https://stackoverflow.com/questions/10506817
复制相似问题