I’m implementing a simple C++ grid class. One Function it should support is accessed through round brackets, so that I can access the elements by writing mygrid(0,0). I overloaded the () operator and i am getting the error message: “non-lvalue in assignment”.
what I want to be able to do:
//main
cGrid<cA*> grid(5, 5);
grid(0,0) = new cA();
excerpt of my implementation of the grid class:
template
class cGrid
{
private:
T* data;
int mWidth;
int mHeight;
public:
cGrid(int width, int height) : mWidth(width), mHeight(height) {
data = new T[width*height];
}
~cGrid() { delete data; }
T operator ()(int x, int y)
{
if (x >= 0 && x <= mWidth) {
if (y >= 0 && y <= mHeight) {
return data[x + y * mWidth];
}
}
}
const T &operator ()(int x, int y) const
{
if (x >= 0 && x <= mWidth) {
if (y >= 0 && y <= mHeight) {
return data[x + y * mWidth];
}
}
}
The rest of the code deals with the implementation of an iterator and should not be releveant.
As Bill remarked, the operator shouldn’t be
const. I believe this is the reason for the compilation error (even if the error reported seems different). The compiler only encounters the error at the assignment line because it is a template class.To be clear, you can’t have a
constmethod return a reference to a non-const. I.e., theproblem is that the declaration
T &operator... constis illegal. It should be eitherT &operator...orconst T &operator... const. Of course you can have both.Edit: Removing the
constdoesn’t help because now both methods have the same signature (the return type is not considered part of the signature for purposes of resolving the call). The method being called is the one returningT, notT &. Get rid of it (or replace it with aconstmethod returning aconstreference.)