2

例如我有这个示例代码:

class Player
{
   int grid;
   Player()
   {
      grid = 0;
   }

}
void main()
{
   Player p;
   ...
   ...
   //now again I want to initialize p here, what to write ?
}

如何再次调用 p 的构造函数?

4

4 回答 4

5

将对象放入本地范围:

while (running)
{
    Player p;  // fresh

    //...
}

每次循环体执行时,Player都会实例化一个新对象。

于 2012-08-09T13:46:39.513 回答
4
class Player
{
   int grid;
   Player()
   {
      grid = 0;
   }

}
void main()
{
   Player p;
   ...
   ...
   //now again I want to initialize p here, what to write ?
   p = Player();
}
于 2012-08-09T13:40:20.293 回答
3

添加init功能。在构造函数中调用它,但也将其公开,以便您以后可以再次调用它。

实际上你可以做任何你想改变状态的函数:

class Player
{
public:
    void setState(/*anything you want*/) {}
};
于 2012-08-09T13:34:43.960 回答
0

加强安德鲁的回答:

class Player
{
public:
    Player()
    {
        reset(); //set initial values to the object
    }

    //Must set initial values to all relevant fields        
    void reset()
    {
        m_grid = 0; //inital value of "m_grid"
    }

private:
    int m_grid;
}


int main()
{
    Player p1;
    Player* p2 = new Player();

    ...
    ...
    p1.reset(); 
    p2->reset(); //Reset my instance without create a new one.
}
于 2012-08-10T15:42:43.993 回答