I have created a menu inside a do-while and when the user chooses what he wants to do the menu appears again. The problem is, for some choices my program has to create objects but when the menu appears again, the object is being destroyed.
我在do-while中创建了一个菜单,当用户选择他想要做的菜单时,菜单再次出现。问题是,对于某些选择,我的程序必须创建对象,但是当菜单再次出现时,对象将被销毁。
Can I stop this from happening?
我可以阻止这种情况发生吗?
Here's the do while:
这是做的时间:
do
{
cout << "What would you like to do?(a,b,c or d)" << endl;
cout << "a. Add a player to a team. " << endl;
cout << "b. View team's stats." << endl;
cout << "c. View player's stats." << endl;
cout << "d. Exit." << endl;
cin >> choice;
cout << endl;
switch(choice)
{
case'a':
cout << "Choose team(1. maxhtes or 2. diashmoi)";
cin >> omada;
addPlayer(omada);
break;
.
.
.
.
}
while(choice != 'd');
And here's the function that creates the element..
这是创建元素的函数..
void addPlayer(int om)
{
if(om ==1)
{
cout << "Give Player's name,sex,occupation,age and the object he has:"
<< endl;
cin >> name1 >> sex1 >> occupation1 >> age1 >> object1;
if(maxhtes.numberOfPlayers==0)
Player player0(name1,sex1,occupation1,age1,object1);
.
.
.
I've skipped the part you don't need.
我跳过了你不需要的部分。
Thanks in advance and sorry for any mistake. First time writing here. :)
提前致谢,对任何错误表示歉意。第一次写这里。 :)
Problem Solved: Created a global array of object and put new objects there. Thanks everyone who tried!
解决问题:创建一个全局对象数组并将新对象放在那里。谢谢大家试过!
2 个解决方案
#1
0
Create the object OUTSIDE the do-while loop. This way, it doesn;t get destroyed when the do-while starts again.
在do-while循环中创建OUTSIDE对象。这样,当do-while再次启动时,它不会被破坏。
Though showing your code would help us help you further.
虽然显示您的代码可以帮助我们进一步帮助您。
#2
0
if(maxhtes.numberOfPlayers==0)
Player player0(name1,sex1,occupation1,age1,object1);
You're creating an object in the scope of the if statement, that object will be destroyed the moment it leaves this scope. Instead, you probably want to save it, in a vector for example:
您正在if语句的范围内创建一个对象,该对象将在离开此范围时被销毁。相反,您可能希望将其保存在向量中,例如:
std::vector<Player> players; // outer scope
//later..
if(maxhtes.numberOfPlayers==0)
players.push_back(Player(name1,sex1,occupation1,age1,object1));
#1
0
Create the object OUTSIDE the do-while loop. This way, it doesn;t get destroyed when the do-while starts again.
在do-while循环中创建OUTSIDE对象。这样,当do-while再次启动时,它不会被破坏。
Though showing your code would help us help you further.
虽然显示您的代码可以帮助我们进一步帮助您。
#2
0
if(maxhtes.numberOfPlayers==0)
Player player0(name1,sex1,occupation1,age1,object1);
You're creating an object in the scope of the if statement, that object will be destroyed the moment it leaves this scope. Instead, you probably want to save it, in a vector for example:
您正在if语句的范围内创建一个对象,该对象将在离开此范围时被销毁。相反,您可能希望将其保存在向量中,例如:
std::vector<Player> players; // outer scope
//later..
if(maxhtes.numberOfPlayers==0)
players.push_back(Player(name1,sex1,occupation1,age1,object1));