我对 C++ 和一般编程还很陌生,所以我一直在寻找简单的场景来测试自己。我想制作一个允许用户输入游戏角色基本数据的程序,但我意识到我无法让用户输入他们想要的角色数量。它们将仅限于我目前允许的那个。我的问题是:在用户完成一个角色并准备创建另一个角色时,我将如何使用什么样的代码来生成该类的另一个对象?如果这些都没有任何意义,这是我的代码:
#include <iostream>
using namespace std;
class character {
public:
string name;
string playerClass;
int health;
};
int main() {
character character1;
cout << "What is your character's name?";
cin >> character1.name;
cout << "What class is your character?";
cin >> character1.playerClass;
cout << "How much health does your character have?";
cin >> character1.health;
//Display info, ask if user wants to make more characters.
return 0;
}
最佳答案
how would, on a user finishing one character and ready to create another, what kind of code would I use to generate another object of the class?
#include <vector>
//...
int main() {
std::vector<character> vCharacters;
bool enter_more = true;
while (enter_more)
{
character character1;
cout << "What is your character's name?";
cin >> character1.name;
cout << "What class is your character?";
cin >> character1.playerClass;
cout << "How much health does your character have?";
cin >> character1.health;
// add new character to vector
vCharacters.push_back(character1);
//Display info, ask if user wants to make more characters.
if ( !user_wants_more_input() )
enter_more = false;
}
// now vCharacters has all the characters entered
return 0;
}
关于c++ - 程序运行时如何创建新变量或对象? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34211963/