0
How to name objects during runtime
Hello! I have a little problem. I am doing a program and I need to create object, whose name is chosen by user. I am doing it in Java, but I have the same problem in C++. String name; cin>>name; Player name; The third line doesn't work. It creates object of type player named "name", but I need it to have name written in the name string variable. Can you help me please?
8 ответов
+ 2
Oh ok. Just use an object vector for this. I think I have a code for showcase....
Here it is:
https://code.sololearn.com/cU2KHvrLZQvl/?ref=app
+ 5
In your code you attemp to create two different variables with the same name in the same scope. It is error in any language. For holding additional data in object use additional field in class (struct) that represents object's type. Eg:
struct Player {
string name;
// ... other data
// declaring constructor for use
Player (string n) : name(n) {}
};
int main() {
string name;
cin >> name;
Player p(name);
}
now object 'p' contains inputed name
+ 1
Or use a map for this. Here is an example:
https://code.sololearn.com/c47udIRQsNo2/?ref=app
The reason this doesn't work like you want to use it is that the string is changed in runtime and the name of the object at compiletime. With a map you can access your object with using the name you gave it as key. It's more complicated then just naming the object yourself so think twice if it is worth it.
+ 1
You can also use the mapping method and fill it in a similar setup as in the object vector code
+ 1
ok, thank you very much. You helped me a lot.
0
Any reason why you want to do that?
0
Thank you for your answers, but consider following situation: I don't know how many players will a user register. I need to name objects p1, p2, p3 ... pn. How can I create for example 10 objects using a cycle and not have to write
Player p1;
Player p2;
Player p3;
...
Player p10;
0
your welcome