0

I would like to generate the name of a soon to be initialized object by getting the user input. Is this possible? Is there a way to name an object based on a variables value?

I know in the code below the "test x" doesn't work and I know why... but is there a way to get this to work? I have been trying to figure it out for 2 days now. The closest thing I came to was maybe stringstreams... or even worse... it isn't possible? Any help?

#include <iostream>
using namespace std;
#include <string>

class test
{
public:
    string wtf;
};

int main()
{
    test y;         // showing normal initialize
    y.wtf = "a";    // assign value


    string x;       
    cin >> x;       // initialize string and get input

    test x          // trying to initialize object based on input
    x.wtf = "a";    // then assign a value


    cout << y.wtf;  // printing both to test
    cout << x.wtf;

    return 0;
}

My intent is to have a single array that holds employee numbers (concatenated with a an "emp" or something in the beginning) to initiate objects for each employee. So the user would input an employee number, say 1234, and I would make a string that added emp + 1234 and come out with "emp1234"... which I would then initiate an object like "test emp1234" which would have a bunch of difference variables associated with it, inside the class.

I may be looking at this all wrong... and probably explained it fairly crappy. I am obviously new to this, but I could use any help possible.

4

2 に答える 2

0

私は次のようにします:

#include <vector>
#include <string>
#include <iostream>
#include <stdexcept>

test make_test()
{
    std::string s;
    if (!(std::cin >> s))
    {
        throw std::runtime_error("Premature end of input");
    }
    return { "emp" + s };
}

int main()
{
    std::vector<test> v;

    for (int i = 0; i != 10; ++i)
    {
         v.push_back(make_test());
         std::cout << "Added employee '" << v.back().wtf << "'\n";
    }
}

これは、ベクトルを 10 個の従業員レコードで埋めます。

于 2013-04-08T21:16:58.030 に答える
0

いいえ、名前が実行時に存在しないという理由だけで、実行時に変数名を作成することはできません。これらは、コンパイル時にのみ役立つ静的構造です。

ただし、実際にはstd::map. これを使用して、整数 (従業員番号) からtestオブジェクトにマップできます。

std::map<int, test> employees;

int employeeNumber;
std::cin >> employeeNumber;

employees[employeeNumber]; // Will default construct a test object mapped to employeeNumber

// Alternatively:
test t( /* some constructor args */ );
employees[employeeNumber] = t;

test次に、たとえば、従業員番号でオブジェクトにアクセスする場合は1234、次のように簡単に実行できます。

employees[1234]
于 2013-04-08T21:18:07.313 に答える