例如我有这个示例代码:
class Player
{
int grid;
Player()
{
grid = 0;
}
}
void main()
{
Player p;
...
...
//now again I want to initialize p here, what to write ?
}
如何再次调用 p 的构造函数?
将对象放入本地范围:
while (running)
{
Player p; // fresh
//...
}
每次循环体执行时,Player
都会实例化一个新对象。
class Player
{
int grid;
Player()
{
grid = 0;
}
}
void main()
{
Player p;
...
...
//now again I want to initialize p here, what to write ?
p = Player();
}
添加init
功能。在构造函数中调用它,但也将其公开,以便您以后可以再次调用它。
实际上你可以做任何你想改变状态的函数:
class Player
{
public:
void setState(/*anything you want*/) {}
};
加强安德鲁的回答:
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.
}