C ++继承:不使用派生类型的基类型的函数签名

时间:2012-10-26 13:42:42

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

由于

2 个答案:

答案 0 :(得分:4)

由于vector<TrainingDataPoint>不是vector<STFDataPoint>的子类型,因此您无法执行此操作。参数类型中的向量不是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;
}

答案 1 :(得分:3)

vector<TrainingDataPoint>类型与vector<STFDataPoint>不同,两者之间没有转化。 vector<A>不是vector<B>的基本类型,即使AB的基础。

可以使用指向容器的指针或指向基类型的智能指针,并更改函数以使用它:

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);