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

标签 c++ inheritance overriding

我有一个名为 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;
    }
};

引用:https://en.wikipedia.org/wiki/Virtual_function

关于c++ - 无法匹配函数定义、模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37090366/

相关文章:

perl - 驼鹿和扩展非驼鹿类

python - 如何覆盖第 3 方安装的应用程序 django 的模型默认方法?

c++ - 类数组求和、索引和计算

ruby - Ruby 中 Class 和 BasicObject 哪个先出现?

api - Odoo 新 API - 覆盖旧 API 函数字段

c# - 无法转换作为派生类的继承类字段

c++ - 在没有正则表达式的情况下验证电子邮件地址

c# - C++ 和 C# 与 Crypto 之间加密的互操作性

c++ - unique_ptr 实现中可能存在的错误

c++ - nvcc 编译器将静态 constexpr 识别为设备代码中未定义