【发布时间】:2013-08-16 12:29:07
【问题描述】:
我想像这样为我的 Source-Plugins 建立一个工厂:
class PluginFactory {
public:
PluginFactory(){};
virtual ~PluginFactory(){};
static MySource* getSourceById(int id, ParameterList& pList){
switch (id){
case 1:
return new StringSource(pList);
default:
std::cout << "Unknown PluginId!" << std::endl;
return nullptr;
}
}
};
MySource 在模式中不能像往常一样抽象,因为它稍后会在模板类中使用。
当我调用返回的MySource* 的方法时,我得到的是超类MySource 的方法,而不是子类StringSource 的重写方法。
任何想法如何解决这个问题?
编辑:
我将超类方法声明为虚拟:
MySource{
...
virtual std::streamsize read(char* s, std::streamsize n){
...
}
};
我在子类的 read-Method 中添加了 override 命令:
class StringSource: public MySource {
...
std::streamsize read(char* s, std::streamsize n) override
{
...
}
};
但它仍然使用超类方法。一定还有别的原因……
顺便说一句。我将 Source-Class 放入 boost::iostream::filtering_istream 中,如下所示:
MySource* source = PluginFactory::getSourceById(1, pluginList[0].second);
boost::iostreams::filtering_istream in;
in.push(*source);
所以我自己不调用 read-method。
【问题讨论】:
-
请向我们展示您实际返回源的代码,并尝试调用它的方法。
-
我自己不调用该方法。我将 Source-Class 推入 boost::iostream::filtering_istream 并在那里调用 read-Method。请参阅上面的编辑。
标签: c++ inheritance factory-pattern