问题描述
我试图创建一个结构数组,它将输入字符串链接到类如下:
I'm trying to create a structure array which links input strings to classes as follows:
struct {string command; CommandPath cPath;} cPathLookup[] = {
{"set an alarm", AlarmCommandPath},
{"send an email", EmailCommandPath},
{"", NULL}
};
将使用如下:
CommandPath *cPath = NULL;
string input;
getline(cin, input);
for(int i = 0; cPathLookup[i] != ""; i++) {
if(cPathLookup[i].command == input)
cPath = new cPathLookup[i].cPath;
}
很明显,这段代码是没有意义的,在输入,我想要cPath被初始化为一个新的AlarmCommandPath或一个新的EmailCommandPath。我可以处理它与一个函数返回一个实例取决于输入,但整个序列的ifs似乎不起眼。
Obviously, this code is meaningless, but I think my intention is apparent - depending on input, I'd like cPath to be initialized as either a new AlarmCommandPath or a new EmailCommandPath. I could handle it with a function returning an instance depending on input, but a whole sequence of ifs just seems inelegant.
我还应该注意,如果它不明显重要的是,AlarmCommandPath和EmailCommandPath派生自CommandPath,CommandPath是一个抽象类。
I should also note that, in case it's not apparent and important, that AlarmCommandPath and EmailCommandPath are derived from CommandPath, and CommandPath is an abstract class.
感谢您提供任何帮助。
编辑:我只是注意到,尽管CommandPath是抽象的,我有一个声明:
I just noticed that, in spite of CommandPath being abstract, I have a declaration:
CommandPath *cPath = NULL;
。为什么要编译?
推荐答案
AlarmCommandPath和EmailCommandPath派生自COmmandPath,正确吗?
AlarmCommandPath and EmailCommandPath are derived from COmmandPath, correct?
在这种情况下,您不能将AlarmCommandPath / EmailCommandPath的实例分配给CommandPath - 它在技术上是可能的,但它不会做你想要的。实例
CommandPath将保留CommandPath的一个实例(它将具有CommandPath的虚拟函数表),无论你分配给它。
In this case you cannot assign an instance of AlarmCommandPath/EmailCommandPath to CommandPath - it is technically possible, but it won't do what you want. The instanceCommandPath will remain an instance of CommandPath (it will have virtual function table of CommandPath), no matter what you assign to it.
你需要使用工厂方法(将返回CommandPath *的函数)。类似的东西:
You need to use factory methods (a function that will return CommandPath*). Something like that:
struct A{
};
struct B: public A{
};
struct C: public A{
};
A* factoryA(){
return new A();
}
A* factoryB(){
return new B();
}
A* factoryC(){
return new C();
}
typedef A* (*FactoryMethod)();
struct{
const char* command;
FactoryMethod factoryMethod;
} factoryTable[] = {
{"A", factoryA},
{"B", factoryB},
{"C", factoryC},
{0,0}
};
这篇关于C ++中的类查找结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!