无法匹配函数定义,模板

Unable to match function definition, template

本文关键字:定义 模板 函数      更新时间:2023-10-16

我有一个名为Box的类,它继承自基类Entity

在实体中,我有getWeight()函数;

double Entity::getWeight() {
    return weight;
}

我想覆盖Box类中的这个函数。所以我这样做了;

template <class T>
double Box<T>::getWeight() {
    return weight + inWeight;
}

但它给了我这个错误

Error   C2244   'Entity::getWeight': unable to match function definition to an existing declaration

为什么我会出现此错误?

编辑:实体类

class Entity {
    public:
        Entity(double weight_in, double length_in, double width_in);
        Entity();
        double getWidth();
        void setWidth(double);
        double getLength();
        void setLength(double);
        double getWeight();
        void setWeight(double);
    protected:
        double weight;
        double length;
        double width;
};

盒式

#include "entity.h"
template <class T>
class Box : public Entity{
    public:
        Box(double weight_in, double length_in, double width_in, double maximumAllowedWeight_in);
        Box();
        Box(Box<T>&);
};

对于Entity类,您也应该执行Alan所说的操作。如果您希望调用Box中的getWeight()方法,当您从声明为Entity类型对象的Box类型对象中调用它时,您应该添加虚拟关键字,以便它实际覆盖(后期绑定):

class Entity {
    float weight = 10;
    virtual double getWeight(){
        return weight;
    }
};

参考:https://en.wikipedia.org/wiki/Virtual_function

您需要在类定义内部声明函数,然后才能在外部定义它。(或者你可以在类中定义它。)

template <typename T>
class Box : public Entity {
    double getWeight();
};

会使你的定义有效。

您可能需要考虑将其标记为const