本文介绍了使用C ++中的字符串进行类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用字符串将基类转换为子类?

像这样的东西?请

Is it possible to type cast a base class to a child class using a string?

Something like this maybe? Please

std::map<cstring,baseclass> types;
types["childClass1"] = childClass1;
.
.
.
CString nameOfClass = getStringFromCLI();

types[nameOfClass] * aChildClass = (types[nameOfClass] *) new baseClass();
//Now aChildClass is of type childClass1 (NOT baseClass)



现在,我有成千上万的子类,不用说,我使用脚本来生成if语句,并相应地将类型转换为baseClass.

欢迎所有想法!但您不必提及我的代码毫无用处,因为我已经知道了.

这是使用Java的方法(来自 [ ^ ]



Right now I have hundreds of thousands of child classes, and needless to say, I use a script to generate if statements and type cast the baseClass accordingly.

All ideas are welcome! but you don''t have to mention that my code is worthless cause I already know that.

Here is how you can do this in Java (from http://www.knowledgesutra.com/forums/topic/32520-can-i-cast-a-string-as-a-class-object/[^]

import java.lang.reflect.*;
import java.awt.*;
......
//Your class in string
 String s="<your class>";
//Get class definition
 Class cls = Class.forName(s);
//Instantiate
 Object obj=cls.newInstance();

推荐答案




这篇关于使用C ++中的字符串进行类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 23:12