2

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>'

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

It says: wrong number of parameters. I created some friend operators and they worked well, but now i cant solve that.
@demonofnight: The code in my (edited) answer compiles fine for me.
If i keeps only the class T it dont work, it seems i need to put the <class T, int R, int C>. It tells me that the number of arguments should be 3 and not 1. The class is template<class T, int C, int R> class Matrix{...} If i fix that with all the 3 parameters, my main tells me that i have a undefined referece to matrix<int, 100, 100>::operator()(int, int)
Thanks, the problem now is, the compiler tells me that i have a undefined reference to matrix<int, 100, 100>::operator()(int, int), so i'm looking if its because of the implementation or if i did something wrong/
1

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.