无法匹配函数定义、模板
Unable to match function definition, template
我有一个名为 Box 的 class 继承自基础 class Entitiy
在实体中,我有 getWeight()
函数;
double Entity::getWeight() {
return weight;
}
我想覆盖 Box class 中的这个功能。所以我这样做了;
template <class T>
double Box<T>::getWeight() {
return weight + inWeight;
}
但是它给我这个错误
Error C2244 'Entity::getWeight': unable to match function definition to an existing declaration
为什么会出现此错误?
编辑:实体class
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;
};
盒子class
#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>&);
};
您需要先在 class 定义中声明函数,然后才能在外部定义它。 (或者您可以在 class 中定义它。)
template <typename T>
class Box : public Entity {
double getWeight();
};
将使您的定义有效。
您可能要考虑将其标记为 const
。
你也应该为实体 class 做艾伦所说的。如果您希望调用 Box 的 getWeight() 方法,当您从声明为 Entity 类型对象的 Box 类型对象调用它时,您应该添加 virtual 关键字,以便它实际上覆盖(后期绑定):
class Entity {
float weight = 10;
virtual double getWeight(){
return weight;
}
};
我有一个名为 Box 的 class 继承自基础 class Entitiy
在实体中,我有 getWeight()
函数;
double Entity::getWeight() {
return weight;
}
我想覆盖 Box class 中的这个功能。所以我这样做了;
template <class T>
double Box<T>::getWeight() {
return weight + inWeight;
}
但是它给我这个错误
Error C2244 'Entity::getWeight': unable to match function definition to an existing declaration
为什么会出现此错误?
编辑:实体class
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;
};
盒子class
#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>&);
};
您需要先在 class 定义中声明函数,然后才能在外部定义它。 (或者您可以在 class 中定义它。)
template <typename T>
class Box : public Entity {
double getWeight();
};
将使您的定义有效。
您可能要考虑将其标记为 const
。
你也应该为实体 class 做艾伦所说的。如果您希望调用 Box 的 getWeight() 方法,当您从声明为 Entity 类型对象的 Box 类型对象调用它时,您应该添加 virtual 关键字,以便它实际上覆盖(后期绑定):
class Entity {
float weight = 10;
virtual double getWeight(){
return weight;
}
};