无法匹配函数定义,模板
Unable to match function definition, template
我有一个名为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
。
相关文章:
- 单独定义模板化嵌套类方法的正确语法
- 定义模板参数的迭代器类型
- 未定义模板"std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator&
- CPP:定义模板时,通用数据类型 T 是类吗?
- 有没有办法在非模板类中定义模板成员#2
- 如何为自定义模板对象创建专门的函数模板
- 定义模板化结构的特征时出现不完整的类型错误
- 具有定义模板还是非模板的友元函数
- 我可以为不同类型集定义模板吗
- 如何在源文件中定义模板函数
- 如何为模板化类的模板化函数定义模板专用化
- 替换包含已弃用的一元函数的自定义模板
- 如何自定义模板以不包含某些类型
- 未定义模板'std::__1::function<int (double, double, double, double)>'的隐式实例化
- 为什么以这种方式在C 中定义模板函数
- 如何使用模板类作为模板参数正确定义模板类中的模板函数
- 自定义模板编程
- 递归std ::函数定义模板类方法
- C 1Z标准如何定义模板功能声明中属性的正确位置
- 定义模板类函数的错误