2016-10-11 6 views
-2

私はテンプレートのMatrixクラスをC++で実装していますが、operator()オーバーロードのエラーに直面しています。ここでは、コードは次のようになります。ベクトルメンバ参照を返すときのエラー

Matrix.hpp:

template <typename T> 
class Matrix { 
    std::vector<T>* _data; 
    int _sx; 
    int _sy; 

public: 
    // CTOR - DTOR 

    Matrix(int sx, int sy); 
    Matrix(Matrix<T> const &other); 
    ~Matrix(); 

    // Operator Overloads 

    Matrix<T>& operator+=(Matrix<T> const &other); 
    Matrix<T>& operator-=(Matrix<T> const &other); 
    Matrix<T>& operator*=(Matrix<T> const &other); 
    Matrix<T>& operator/=(Matrix<T> const &other); 
    Matrix<T>& operator=(Matrix<T> const &other); 
    T& operator()(int x, int y); 


    // Member Functions 
    void display() const; 
    int getSx() const; 
    int getSy() const; 

private: // Private Member functions 

    bool _rangeCheck(int x, int y) const; 
}; 

#include "../srcs/Matrix.inl" 

Matrix.inl(問題の一部)

template <class T> 
T& Matrix<T>::operator()(int x, int y) { 
    if (this->_rangeCheck(x, y)) { 
     return (this->_data[(y * this->_sx) + x]); 
    } 

    throw std::out_of_range("Bad argument"); 
} 

myMatrix(1, 0) = 1を行うとき、私はこのエラーを受け取るコンパイル中:

./include/../srcs/Matrix.inl:65:9: error: non-const lvalue reference to type 'int' cannot bind to a value of unrelated type 'std::vector<int>' 
    return (this->_data[(y * this->_sx) + x]); 

私が間違っていることは何ですか?あなたのdata

+4

'(* this - > _ data)[(y * this - > _ sx)+ x]'、私はそれを誤字としてとらえます。しかし...なぜポインタになるには '_data'が必要でしょうか? – LogicStuff

+2

テンプレートの実装はヘッダーに入ります。 ...の複製...どこかで – UKMonkey

+1

'#include" matrix.cpp "' <---ちょうどしないでください。あなたはちょうど今のようにエラーで終わるでしょう –

答えて

3
(this->_data[(y * this->_sx) + x]); 

は、それがstd::vector<T>の配列としてdataにアクセスしている上そうoperator[]を使用して、ポインタです。

template <typename T> 
class Matrix 
{ 
    std::vector<T> _data; 
    //... 
}; 

template <typename T> 
class Matrix : private std::vector<T> 
{ 
    //... 
}; 

EDIT:

をmolbdniloのコメントで指摘したように、標準コンテナを継承することであるあなたがここにポインタを避け、またはstd::vectorを継承考えるかもしれ

(*(this->_data)[(y * this->_sx) + x]); 

:とそれを交換してくださいお勧めしません。

理由を理解するためにthis questionを参照してください。

+1

私は継承をお勧めしません。標準的なコレクションは、個人的にさえ継承されることはありません。 – molbdnilo

+0

@molbdniloあなたが正しいです、私はここでの結果を過小評価していました。私は自分の答えを編集した – wasthishelpful

関連する問題