2

我有以下代码:

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(不是它们的向量),它运行正常。有人可以解释为什么会这样以及是否有解决方法?

谢谢

4

2 回答 2

4

因为vector<TrainingDataPoint>不是vector<STFDataPoint>你的子类型,所以不能这样做。向量在参数类型中不是协变的。

但是,您可以使用模板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;
}
于 2012-10-26T13:51:15.600 回答
3

类型vector<TrainingDataPoint>不一样,vector<STFDataPoint>两者之间没有转换。vector<A>不是 的基类型vector<B>,即使A是 的基B

可行的是拥有一个指向基本类型的指针或智能指针容器,并更改函数以使用它:

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

std::vector<std::unique_ptr<STFDataPoint>> b;
b.push_back( std::unique_ptr<STFDataPoint>(new TrainingDataPoint(1,2,"",left, right, "") ); // fill with any derived types of STFDataPoint
do_something(b);    
于 2012-10-26T13:48:54.413 回答