问题
for example lets say your pulling data from somewhere and you put it in a string variable then you want to use the data inside of it to be the another strings name:
int main(void){
string strVar ="StringData"; //this is a string variable with text inside
cout<<strVar<<endl; //displaying the variables contents
string strVar.c_str() = "stuff in string variable 'StringData'"; //this uses what was inside of strVar to be the name of the new string variable
cout<<StringData<<endl; //prints the contents of the variable StringData (who got its name from the data inside of strVar
}
//OUTPUT:
StringData
stuff in string variable 'StringData'
i know you definitely cannot do it in this manner and in this example your would have to know before hand what was in strVar before you used the variable StringData, but can we theoretically do this?
Edit:
Thanks everyone, so what i get from you all is basically its not possible, C++ is not a Dynamic variable language and the closest thing i can get to it is with a map (string, string)
回答1:
Nothing explicitly like you are thinking, but maybe you'd be interested in a std::map
? Sounds like what you want is a Key-Value pairing.
Reference for std::Map -> http://www.cplusplus.com/reference/stl/map/
Example:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
map<string, string> myMap;
myMap.insert(pair<string, string>("StringData", "Stuff in StringData"));
// Get our data
cout << myMap["StringData"] << endl;
return 0;
}
回答2:
Variable names exist only at compile time in C++. The closest you can come is to use a map with string keys.
回答3:
I'm not sure what you're asking, but if you want to have "dynamic" variable names, then you can't do that in the code directly. You would have to use some map-type data construct. Look at std::hash_set
or std::map
if you can use the standard library.
回答4:
There are languages where you can create variables dynamically. C++ isn't one of them ;)
来源:https://stackoverflow.com/questions/11183429/declare-variables-names-using-string-value-data-in-cpp-c