我需要一种基于作为std :: string传递的类名来实例化对象的方法.这项目前正在发挥作用,但需要进行概括:
void* create(std::string name) {
if(name == "classOne") return new ClassOne();
else if(name == "classTwo") return new ClassTwo();
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
我没有的东西:
还有别的什么.
最佳用例场景将是:
int main() {
void *obj = create("classTree"); // create object based on the string name
/* ... */
// once we know by context which specific class we are dealing with
ClassTree *ct = (ClassTree*)obj; // cast to appropiate class
std::cout << ct->getSomeText() << std::endl; // use object
} …Run Code Online (Sandbox Code Playgroud) c++ ×1