trying to make a simple grid-class, non-lvalue in assignment

Posted by Tyrfing on Stack Overflow See other posts from Stack Overflow or by Tyrfing
Published on 2010-02-11T14:01:55Z Indexed on 2010/04/10 18:43 UTC
Read the original article Hit count: 402

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about operators