C++ 无法匹配函数定义、模板

C++ 无法匹配函数定义、模板,c++,inheritance,overriding,C++,Inheritance,Overriding,我有一个名为Box的类继承自基类Entitiy 在实体中,我有getWeight()函数 double Entity::getWeight() { return weight; } 我想在Box类中重写此函数。所以我就这样做了, template <class T> double Box<T>::getWeight() { return weight + inWeight; } 为什么我会犯这个错误 编辑:实体类 class Entity {

我有一个名为Box的类继承自基类Entitiy

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

double Entity::getWeight() {
    return weight;
}
我想在Box类中重写此函数。所以我就这样做了,

template <class T>
double Box<T>::getWeight() {
    return weight + inWeight;
}
为什么我会犯这个错误

编辑:实体类

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.h”
模板
类框:公共实体{
公众:
箱子(双倍重量英寸、双倍长度英寸、双倍宽度英寸、双倍最大允许重量英寸);
Box();
盒子(盒子&);
};

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

模板
类框:公共实体{
双getWeight();
};
会使你的定义有效


您可能需要考虑对其进行标记>代码> const >

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

模板
类框:公共实体{
双getWeight();
};
会使你的定义有效


你可能想考虑标记它>代码> const 。

你也应该按照艾伦所说的对实体类做。如果您希望调用Box中的getWeight()方法,那么当您从声明为实体类型对象的Box类型对象调用它时,应该添加virtual关键字,以便它实际覆盖(后期绑定):


参考资料:

您应该按照Alan对Entity类所说的做。如果您希望调用Box中的getWeight()方法,那么当您从声明为实体类型对象的Box类型对象调用它时,应该添加virtual关键字,以便它实际覆盖(后期绑定):


参考资料:

您如何声明
实体
?请出示相关代码。您如何声明
实体
?请出示相关代码。
#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>&);
};
template <typename T>
class Box : public Entity {
    double getWeight();
};
class Entity {
    float weight = 10;
    virtual double getWeight(){
        return weight;
    }
};