gpt4 book ai didi

C++调用子类的虚方法而不是基类

转载 作者:行者123 更新时间:2023-11-30 01:17:49 24 4
gpt4 key购买 nike

我有一个基类 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方法。我不能在基类中使用纯虚函数,因为必须创建此类的对象。

最佳答案

您需要更改 map<int, Feature<Text>>map<int, Feature<Text>*> .要通过其基调用多态函数,您需要一个间接级别,例如指针或引用。

关于C++调用子类的虚方法而不是基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com