【问题标题】:C++ Call virtual method of child class instead of base classC++调用子类的虚方法而不是基类
【发布时间】: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


【解决方案1】:

您需要将map&lt;int, Feature&lt;Text&gt;&gt; 更改为map&lt;int, Feature&lt;Text&gt;*&gt;。要通过其基调用多态函数,您需要一个间接级别,例如指针或引用。

【讨论】:

    【解决方案2】:

    只需在这一行添加一个指针*map&lt;int, Feature&lt;Text&gt;&gt; features

    所以它是这样的:map&lt;int, Feature&lt;Text&gt;*&gt; features

    【讨论】:

      猜你喜欢
      • 2011-01-05
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 2016-10-05
      • 1970-01-01
      相关资源
      最近更新 更多