class - Matrix Multiplication with template parameters in C++ -
i have self-defined matrix
class , want overload operator *
matrix multiplication:
template< int r, int c> class matrix{ int *_mat; int _size; public: matrix(){ _size = r*c; _mat = new int[_size]{0}; } ~matrix(){ delete []_mat; } matrix &operator=(const matrix & m){/*...*/} //... template< int d2, int d1 > using matrix_t = int[d2][d1]; template<int r2, int c2> matrix<r,c2> operator*(const matrix_t<r2,c2> &mat) { matrix<r,c2> result; for(int r = 0; r < r; r++) { for(int c = 0; c < c2; c++) { for( int i; < c; i++ ){ /*do multiplication... result._mat[r*c2+c] = ... */ } } } return result; } //... };
then problem comes matrix<r,c2> result
. result
becomes outside object of class. cannot access private member using result._mat[r*c2+c]
.
what solution( without changing access permission) define function of matrix multiplication in class?
you specify operator can externally set values of matrix. note won't able use operator []
- since can use 1 argument (ref c++ [] array operator multiple arguments?)
int& operator() (int row, int col) { // todo: check array bounds return _mat[c*row+col]; }
usage:
result(r,c) = ...
Comments
Post a Comment