我有以下代码:
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/