How to define variable according to string. I had defined many classes.But I want to creat variable of this class according to some string.
The code looks like this.
class AA {};
class BB {};
class CC {
CC(void *pt);
virtual ~CC();
};
......
void test(char *ss,void *pt=NULL) {
//??????How to do?
}
int main() {
a1=test("AA"); //a1=new AA();
a2=test("AA"); //a2=new AA();
b1=test("BB"); //b1=new BB();
c1=test("CC",pt); //c1=new CC(pt);
}
Orther,you can consider this as URL and handle function.The std::map is common method to get instance of class according to string.But can’t create a new instance to variable. I hope get a new instance according to string.
C++ is a strongly typed language, so this isn’t possible as you have it now.
Best case, you’d use a common base class for
AA,BB,CCand then use a factory. You can’t just write:without defining a type for the variables.
For example:
Alternitively, you should use smart pointers. If you don’t you’ll have to manage the memory yourself.