2012-05-08 175 views
0

这样可以吗?即时通讯基本上用一个封装了所有游戏实体和逻辑的类来代替对引用全局变量的单个函数的调用,下面是我想如何在main中调用新类,只是想知道在这方面一般的C++大师共识是什么。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; 
} 
+2

呃,为什么不把'loop'作为自己的函数呢? –

+1

而不是主要在阳光下做所有事情你做了一个封装另一个函数的类,它在构造函数中调用了太阳下的所有东西。我不会称之为设计模式。 – AJG85

+0

这是什么问题? –

回答

9

这不是常见的有包含游戏/事件/ ...循环,通常的方式做这样的东西是使用构造函数来设置对象的构造,然后提供一个单独的方法开始了漫长的阐述。

像这样:

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 
} 
+0

所以最好不要在构造函数中调用loop(),只需创建一个类thingy的实例,然后调用该对象的循环? –

+0

这是通常的方法。 –

+0

看起来我又太慢了! – dreamlax

7

我不是一个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; 
} 

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