C++ 设计模式
c++ design pattern
可以吗? 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;
}
构造函数用于构造对象,而不是用于处理整个应用程序的逻辑。同样,如果需要,应在构造函数中适当处理在构造函数中获取的任何资源。
相关文章:
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 资源管理设计模式
- 用于在回调中调用解析器的设计模式
- 设计帮助 - 为不同类型的消息处理通用接口的设计模式
- 在这种情况下我应该使用哪种设计模式
- C++中物体改变识别的设计模式?
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 需要实例化不同类/对象并在启动时确定的硬件插槽的设计模式
- 设计模式,以避免不必要地添加抽象函数以适应新功能
- 工厂设计模式优化
- 使用C++模板的数据映射器设计模式
- 为什么以及如何使用原型设计模式
- 具有多个继承共享一个资源的对象 - 寻找良好的设计模式
- 在C++中创建观察器设计模式的好方法
- 现代C++在多大程度上消除了对设计模式的需求?
- 对于存储另一个类所需信息的类,例如其构造,是否有设计模式?
- 下面抽象工厂设计模式的实现是正确的吗
- sql记录集函数的状态设计模式
- 是否有可以处理方法调用依赖关系的设计模式?
- 使用 C++ 设计模式