Overloading the parenthesis operator

I'm trying to make 2d matrix-type grayscale image class whose elements can be accessed with the parenthesis operator like:

1
2
3
4
Image mat;
mat(2,3) = 5;
int x;
x = mat(2,3);


When I try to build the code below, I get an error that says
error C2440: 'return' : cannot convert from 'int' to 'int &'
. I don't know what I'm doing wrong here. Here's the class so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Image
{
public:
   int &operator() (int, int);
private:
   int rows;
   int cols;
   unsigned short *imageData;
};

int &Image::operator() (int r, int c)
{
   if(r < rows && c < cols)
      return (int)imageData[r * cols + c];
   else
      return -1;
}
Make the operator() function return int instead of int &


Edit:
I thought I better add that you can't make a reference of a numeric literal,
which is the cause of the error.
Last edited on
First of all, -1 isn't a reference of any variable, it's just a numeric literal, about the first return, you need to cast int correctly, if you want to return a reference of unsigned short* imageData then you have to cast it to (int&) like return (int&) imageData[r * cols + c].

I think that you are using class optimization methods but you must understand them better before trying to do it.
This is exactly a case where exceptions fit the bill.

else throw std::range_error( "row or col out of range" );
Topic archived. No new replies allowed.