根据字符串定义变量

define variable according to string

本文关键字:变量 定义 字符串      更新时间:2023-10-16

如何根据字符串定义变量。我定义了很多类。但是我想根据某个字符串创建此类的变量。

代码如下所示。

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++是一种强类型语言,所以这是不可能的,因为你现在拥有它。

最好的情况是,你可以对AABBCC使用一个公共基类,然后使用工厂。你不能只写:

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);
}