How to call my superclass method?
May 30, 2020 at 8:07am UTC
I came up with the idea, overloading the opertor[] method from std::vector, within it i need to call std::vector's own operator[] method, but I got stuck with.
Here the code I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include <vector>
#include <iostream>
template <typename T>
class Matrix : public std::vector<T>
{
size_t row_size, col_size;
struct Row {
Matrix<T> & mat;
size_t row;
Row( Matrix<T> & m, size_t r )
: mat{m}, row{r}
{}
// how could I invoke std::vector's operator[] method?
T & operator [] ( size_t col ) {
return std::vector<T>::operator []( row * mat.col_size + col );
}
};
public :
Matrix( size_t rows, size_t cols)
: row_size{rows}, col_size{cols}, std::vector<T>(rows*cols)
{}
Row operator [] ( size_t row ) { return Row( *this , row ); }
};
int main()
{
size_t ROWS = 5, COLS = 10;
Matrix<int > mat( ROWS, COLS );
for ( size_t row = 0; row < ROWS; ++ row)
for ( size_t col = 0; col < COLS; ++ col)
mat[row][col] = (row+1) * (col+1);
for ( size_t row = 0; row < ROWS; ++ row) {
for ( size_t col = 0; col < COLS; ++ col) {
std::cout << mat[row][col] << '\t' ;
}
std::cout << '\n' ;
}
}
I get this error:
matrix_3.cpp: In instantiation of ‘T& Matrix<T>::Row::operator[](size_t) [with T = int; size_t = long unsigned int]’:
matrix_3.cpp:37:25: required from here
matrix_3.cpp:18:47: error: cannot call member function ‘std::vector<_Tp, _Alloc>::reference
std::vector<_Tp, _Alloc>::operator[](std::vector<_Tp, _Alloc>::size_type) [with _Tp = int;
_Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::reference = int&; std::vector<_Tp, _Alloc>::size_type
= long unsigned int]’ without object
18 | return std::vector<T>::operator[]( row * mat.col_size + col );
| ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
Thanks for help.
Last edited on May 30, 2020 at 8:09am UTC
May 30, 2020 at 8:58am UTC
The object Matrix inherits from Vector, but your operator[] is part of the Row class. I see that your Row class does contain a Matrix object named mat ; did you meant to call it on that Matrix object?
return mat .std::vector<T>::operator []( row * mat.col_size + col );
May 30, 2020 at 9:24am UTC
Thank you Repeater!
Topic archived. No new replies allowed.