C++ 继承 : function signatures for base type not working with derived type

标签 c++ inheritance function-signature

我有以下代码:

class STFDataPoint {
public:

    virtual ImagePoint get_patch_top_left() const = 0;
    virtual ImagePoint get_patch_bottom_right() const = 0;
    virtual std::string get_image_filename() const = 0;

    virtual ~STFDataPoint() = 0;
};
inline STFDataPoint::~STFDataPoint() {}


class TrainingDataPoint : public STFDataPoint{
private:
    int row;
    int col;
    std::string class_label;
    ImagePoint patch_top_left;
    ImagePoint patch_bottom_right;
    std::string image_filename;
public:
    TrainingDataPoint(int row, int col, std::string class_label, 
            const ImagePoint & top_left, 
            const ImagePoint & bottom_right, 
            std::string image_filename);

    std::string get_class_label() const;

    inline bool operator==(const TrainingDataPoint& other) const{
        return other.class_label == this->class_label;
    }
    inline bool operator!=(const TrainingDataPoint& other) const{
        return !(*this == other);
    }

    virtual ImagePoint get_patch_top_left() const;
    virtual ImagePoint get_patch_bottom_right() const;
    virtual std::string get_image_filename() const;

};

我正在尝试运行以下命令:

bool do_something(vector<STFDataPoint>& data_point){
    return true;
}


int main(int argc, char* argv[]) {

    ImagePoint left = ImagePoint(2,3);
    ImagePoint right = ImagePoint(2,3);

    TrainingDataPoint a = TrainingDataPoint(1,2,"",left, right, "");
    vector<TrainingDataPoint> b;
    b.push_back(a);

    do_something(b);
}

但是得到如下错误:

invalid initialization of reference of type ‘std::vector<STFDataPoint>&’ from expression of type `std::vector<TrainingDataPoint>`

但是,如果我更改 do_something() 的签名以接收 STFDataPoint(不是它们的 vector ),它运行良好。有人可以解释为什么会这样吗,以及是否有解决方法?

谢谢

最佳答案

vector<TrainingDataPoint>不是 vector<STFDataPoint> 的子类型你不可以做这个。 vector 不是 covariant在参数类型中。

但是你可以模板do_something使其工作:

template <typename T>
bool do_something(vector<T>& data_point){
   //common actions like
   ImagePoint leftPatch = data_point[0].get_patch_top_left();
   return true;
}

关于C++ 继承 : function signatures for base type not working with derived type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13088099/

相关文章:

c++ - 在没有 new[] : Pointer to Base vtable is bad 的情况下分配 Derived 数组

C++数据结构保持插入顺序并能够通过键查找

java - 了解类变量的继承

Java派生子类对象无法解析符号

rust - 文档是否提到在函数参数前面添加 `mut` 关键字的可能性?

c++ - 自动用指向部分专用函数成员的指针填充 vector

c++ - 随机数独生成

c++ - 放大 Qt 小部件,使其覆盖其他小部件

java - 更改类和对象。 (其他方法?)

perl - 如何在签名中声明可选参数?