0

I am trying to find a way to call an object's members, but using a user input to determine which object. So, I have 3 objects: obj1, obj2, obj3. I then ask a user to enter which object they want to manipulate. Then using this input, I call the respective object's member function.

string input;
cin >> input; 
input.memberfunc();//where input is obj1, for example

I understand that this is obviously not the way, and that I would firstly have to convert the string etc., but would appreciate any advise on the best way to achieve my requirement.

4

3 に答える 3

0

オブジェクトの配列を作成できます

Object *objects[3] = {&obj1, &obj2, &obj3};
int index;
cin >> index;
if ((index > 0) && (index < 4))
{
   object[index]->memberfunc();
}

または、文字列で選択する場合は、マップを使用して実行できます。

std::map<std::string, Object *> objectmap;
objectmap["obj1"] = &obj1;
objectmap["obj2"] = &obj2;
objectmap["obj3"] = &obj3;
std::string input;
cin >> input;
if (objectmap.find(input) != objectmap.end())
{
    objectmap[input]->memberfunc();
}
于 2013-04-22T21:35:50.617 に答える
0

@VX 回答を使用して本を動的に追加する:

std::map<std::string, Book* > bookmap;
bookmap["obj1"] = &obj1;
bookmap["obj2"] = &obj2;
bookmap["obj3"] = &obj3;

//Dynamically loaded book:    
Book* newBook = new Book(/* any arguments you need */);
bookmap[ newBook->getIdentifier() ] = newBook;

std::string input;
cin >> input;
if (bookmap.find(input) != bookmap.end())
{
    bookmap[input]->bookmap();
} else {
    cerr << "Error: book '" << input << "' not found." << endl;
}
于 2013-04-23T01:58:33.550 に答える