【发布时间】:2011-02-19 20:01:45
【问题描述】:
我正在尝试创建一个将输入字符串链接到类的结构数组,如下所示:
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 序列似乎并不优雅。
我还应该注意,AlarmCommandPath 和 EmailCommandPath 是从 CommandPath 派生的,并且 CommandPath 是一个抽象类。
感谢您提供的任何帮助。
编辑:我刚刚注意到,尽管 CommandPath 是抽象的,但我有一个声明:
CommandPath *cPath = NULL;
在工作代码中。为什么会编译?
【问题讨论】:
标签: c++ class inheritance pointers