0

如何根据字符串定义变量。我已经定义了很多类。但是我想根据一些字符串创建这个类的变量。

代码看起来像这样。

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 是根据字符串获取类实例的常用方法。但不能为变量创建新实例。我希望根据字符串得到一个新的实例。

4

3 回答 3

5

C++ 是一种强类型语言,所以这在你现在拥有它是不可能的。

最好的情况是,您将使用通用基类AA, BBCC然后使用factory。你不能只写:

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

Alternitively, you should use smart pointers. If you don't you'll have to manage the memory yourself.

于 2012-09-24T11:38:01.310 回答
1

You probably want you function to return something, either void* or, preferably, a [smart] pointer to a common base. The string should probably be passed as char const* or as std::string const&. Within the function you either directly compare the argument and you call the appropriate allocation or you create a std::map<std::string, FactoryFunction> to look up a factory function based on the string.

于 2012-09-24T11:43:05.750 回答
0

Maybe instead of using string names of types - use types as they are. To do this - use templates.

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);
}
于 2012-09-24T12:07:11.507 回答