In C++ when we create object the constructor initi

2019-07-09 13:32发布

For example I Have this example code:

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

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

How do I call the constructor of p again ?

标签: c++ oop
4条回答
神经病院院长
2楼-- · 2019-07-09 14:24
class Player
{
   int grid;
   Player()
   {
      grid = 0;
   }

}
void main()
{
   Player p;
   ...
   ...
   //now again I want to initialize p here, what to write ?
   p = Player();
}
查看更多
\"骚年 ilove
3楼-- · 2019-07-09 14:25

Add init function. Call it in constructor, but also make it public, so you can call it later again.

Actually you can make any function you want to change the state:

class Player
{
public:
    void setState(/*anything you want*/) {}
};
查看更多
Bombasti
4楼-- · 2019-07-09 14:26

Put the object into a local scope:

while (running)
{
    Player p;  // fresh

    //...
}

Each time the loop body executes, a new Player object is instantiated.

查看更多
不美不萌又怎样
5楼-- · 2019-07-09 14:27

Reinforcing Andrew's answer:

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.
}
查看更多
登录 后发表回答