-2

I'm implementing a template Matrix class in c++ and I'm facing an error for operator() overloading. Here is the code:

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 (Problem part)

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

While compiling I receive this error when doing 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]);

Any idea of what I'm doing wrong?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
JM445
  • 168
  • 1
  • 12

1 Answers1

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

Your data is a pointer, so using operator[] on it is accessing data as an array of std::vector<T>. Replace it with:

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

You may consider avoiding pointer here, or inheriting std::vector:

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

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

EDIT:

As pointed in the comments by molbdnilo, inheriting a standard container is not recommended.

See this question to understand why.

Community
  • 1
  • 1
rocambille
  • 15,398
  • 12
  • 50
  • 68