根据字符串定义变量
define variable according to string
如何根据字符串定义变量。我定义了很多类。但是我想根据某个字符串创建此类的变量。
代码如下所示。
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);
}
或者,您可以将其视为URL和句柄函数。std::map 是根据字符串获取类实例的常用方法。但无法创建要变量的新实例。我希望根据字符串获得一个新实例。
C++是一种强类型语言,所以这是不可能的,因为你现在拥有它。
最好的情况是,你可以对AA
、BB
、CC
使用一个公共基类,然后使用工厂。你不能只写:
a1=test("AA"); //a1=new AA();
a2=test("AA"); //a2=new AA();
b1=test("BB"); //b2=new BB();
c1=test("CC",pt); //b2=new CC(pt);
无需为变量定义类型。
例如:
class Base{};
class AA : public Base {};
class BB : public Base {};
Base* create(const std::string& what)
{
if (what == "AA")
return new AA;
if (what == "BB")
return new BB;
return NULL;
}
int main()
{
Base* a;
a = create("AA");
}
或者,您应该使用智能指针。如果你不这样做,你将不得不自己管理内存。
你可能希望你的函数返回一些东西,要么是void*
,要么是指向公共基的[智能]指针。字符串可能应该作为char const*
或std::string const&
传递。在函数中,您可以直接比较参数并调用适当的分配,或者创建一个std::map<std::string, FactoryFunction>
来查找基于字符串的工厂函数。
也许不是使用类型的字符串名称 - 而是按原样使用类型。为此 - 使用模板。
class AA {};
class BB {};
class CC {
public:
CC(void *pt) {}
virtual ~CC() {}
};
template <class T>
T* test() {
return new T();
}
template <class T>
T* test(void *pt) {
return new T(pt);
}
int main() {
void* pt;
AA* a1=test<AA>(); //a1=new AA();
AA* a2=test<AA>(); //a2=new AA();
BB* b1=test<BB>(); //b1=new BB();
CC* c1=test<CC>(pt); //c1=new CC(pt);
}
相关文章:
- 用C++中的一个变量定义一个常量
- 变量定义到C++布尔值转换
- 未声明的标识符错误,但变量定义正确 (?)
- C++多线程程序:变量定义为类成员的隔离错误
- 将变量定义为静态时,为什么可以多次定义它
- 初始值设定项列表与构造函数赋值与变量定义
- 如何根据传递给函数的变量定义特征矩阵大小
- C++ 描述如何使用来简化变量定义
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 是否修改其声明语句中的变量定义良好
- 使用类的其他成员变量定义类的成员变量数组
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 元组 std::get() 不适用于变量定义的常量
- 全局使用变量定义和C 声明
- C++变量定义中的易失性类型量词位置
- 将变量定义为数组和正确的语法
- 多个,包括具有变量定义的头文件
- 调用构造函数,并将成员作为参数解析为变量定义
- 逗号分隔变量定义中关系前的序列
- 如何使用命名变量定义常量右值引用参数的默认值