【发布时间】:2014-05-12 00:17:07
【问题描述】:
我有一个基类Feature
feature.h
#ifndef FEATURE_H
#define FEATURE_H
#include <string>
#include <map>
using namespace std;
template <class T> class Feature
{
public:
virtual map<string, double> calculate(T input)
{
map<string, double> empty;
return empty;
}
};
#endif FEATURE_H
还有一个子类AvgSentenceLength
avgSentenceLength.h
#include "text.h"
#include "feature.h"
class AvgSentenceLength : public Feature<Text>
{
public:
map<string, double> calculate(Text text);
};
我尝试使用AvgSentenceLength 对象从另一个文件调用calculate 方法,但不是直接但仍然:
map<int, Feature<Text>> features;
AvgSentenceLength avgSentenceLength;
features.insert(pair<int, Feature<Text>>(1, avgSentenceLength));
map<string, double> featuresValues;
featuresValues = features.at(1).calculate(text);
我想调用子类的calculate方法,却调用了基类的calculate方法。我不能在基类中使用纯虚函数,因为需要创建这个类的对象。
【问题讨论】:
-
虽然这似乎不是问题,但在 C++11 中,如果您搞砸并意外引入了一个新函数通过名称中的拼写错误或不同的参数类型,编译器将发出错误
标签: c++ polymorphism virtual