我有一个名为 Box 的类继承自基类 Entitiy
在实体中,我有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 类型对象调用它时,您应该添加 virtual 关键字,以便它实际上覆盖(后期绑定(bind)):
class Entity {
float weight = 10;
virtual double getWeight(){
return weight;
}
};
关于c++ - 无法匹配函数定义、模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37090366/