c++ - 程序运行时如何创建新变量或对象? (C++)

标签 c++ class variables object

我对 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?

使用 std::vector<character> :

#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/

相关文章:

javascript - 在 Node.js 中导出变量的推荐方法

JavaScript 函数变量

c++ - C++ 中的可扩展第一人称射击游戏?

c++ - 在 C++ 应用程序中集成 ANTLR 4

c++ - 在没有QFile的情况下在QT中读取文本文件

javascript - CoffeeScript 类中是否可以有同名的静态函数和成员函数?

python - Cython:如何将 python 对象作为 cython 类的属性

python - python 类中的条件

c - 为什么我得到结果=0.00000

c++ - 有没有包含 Wii Motion Plus 的好的 Wiimote API (C/C++)?