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>ではなく、2つの間の変換はありません。がのベースであっても、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);    
于 2012-10-26T13:48:54.413 に答える