Reputation: 11
I'm building a wrapper class for a single pointer that acts as a TwoD array.
I have an overloaded operator() for returning a value from the array.
I want to be able to use operator() for accessing array values of the form arr(r,c)
#include <iostream>
#include <cstring>
using namespace std;
template <class T>
class TwoDArray
{
private:
T * arr;
int rows, columns, size;
int getIndex(int r, int c)
{
int index = (r*columns) + c;
return index;
}
public:
/*Constructor*/
TwoDArray(int r = 1, int c = 1) : rows(r), columns(c)
{
if(r > 0 && c > 0)
{
size = rows*columns;
arr = new T [size];
memset(arr, 0, sizeof(int)*size);
}
else
{
arr = NULL;
}
}
void setAtIndex(int r, int c, T value)
{
int index = getIndex(r, c);
arr[index] = value;
}
//lvalue - has the effect obj(r,c);
T& operator()(unsigned int r, unsigned int c)
{
if(r >= rows || c >= columns)
{
cerr<<"Unable to locate memory\n";
exit(0);
}
return arr[getIndex(r,c)];
}
//rvalue - has the effect obj(r,c);
const T& operator()(unsigned int r, unsigned int c) const
{
if(r >= rows || c >= columns)
{
cerr<<"Unable to locate memory\n";
exit(0);
}
return arr[getIndex(r,c)];
}
void displayTwoD() const
{
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
cout<<this->arr(i,j);
}
cout<<"\n";
}
}
/*Destructor*/
~TwoDArray()
{
if(arr != NULL)
delete arr;
arr = NULL;
}
};
int main()
{
TwoDArray <int> tda(5,5);
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
tda.setAtIndex(i,j, (i+1)*2);
}
}
tda.displayTwoD();
return 0;
}
I get the error:
G:\DS>g++ checkError.cpp
checkError.cpp: In instantiation of 'void TwoDArray<T>::displayTwoD() const [with T = int]':
checkError.cpp:95:18: required from here
checkError.cpp:68:10: error: expression cannot be used as a function
cout<<this->arr(i,j);
when I use
cout<<arr(i,j);
anywhere in the code. I want to know why this happens and how to solve it.
Upvotes: 0
Views: 1106
Reputation: 763
EDIT: Now I see what you want to do. You want to call the operator() from within a member function. You can do this by de-referencing "this":
(*this)(i,j)
Old answer, but made no sense:
TwoDArray::arr is a pointer, you need to de-reference it: (*arr)(i,j)
Upvotes: 2