Reputation: 1768
I'm doing a homework that needs to be done using templates: it's a matrix class.
One of tells me to overload the operator ()(int r, int c);
, so I can access my data using obj(a, b);
or change it with obj(a, b)=100;
.
The template for my class is template<class T, int C, int R>;
Then I created inside my class in the public scope a:
T& operator()(int r, int c);//LINE 16
The implementation is simple.
I tried in 2 ways:
template <class T>
T& Matrix::operator()(int r, int c){
return matrixData[r][c];
}
template <class T, int C, int R>
T& Matrix::operator()(int r, int c){
return matrixData[r][c];
}
In the last one I get the error telling me:
16: Error: expected type-specifier before '(' token
the line 16 is above with a commentary error:
no 'T& Matrix<T, C, R>::operator()(int, int)' member function declared in class 'Matrix<T, C, R>'
Upvotes: 2
Views: 265
Reputation: 500913
The class is
template<class T, int C, int R> class Matrix {...}
:
The following works for me:
#include <iostream>
template<typename T, int R, int C>
class Matrix {
T data[R][C];
public:
T& operator()(int r, int c);
};
template <typename T, int R, int C>
T& Matrix<T, R, C>::operator()(int r, int c) {
return data[r][c];
}
int main() {
Matrix<int, 3, 4> m;
m(0, 1) = 42;
std::cout << m(0, 1) << std::endl;
}
Upvotes: 3
Reputation: 19347
If I understand correctly you're missing the type on Matrix
:
template <class T>
T& Matrix<T>::operator()(int r, int c){
return matrixData[r][c];
}
template <class T, int C, int R>
T& Matrix<T>::operator()(int r, int c){
return matrixData[r][c];
}
Upvotes: 1