The vector class provides access and altering uses brackets, e.g. v[5]. How can I make a class that can do the same? e.g. given Class Test object t, t[5]=...

Recommended Answers

All 2 Replies

Here is a simple example. You need to overload the [] operator, as below.

const int MAXSIZE = 20;
class MyClass
{
public:
    MyClass() 
    { 
        x = 0; 
        for(int i = 0; i < MAXSIZE; ++i)
            array[i] = i+1;
    }
    int& operator[](int n) {return array[n];}
private:
    int x;
    int array[MAXSIZE];
};


int main()
{
    MyClass mc;
    int n = mc[4];
    cout << n << "\n";
    mc[4] = mc[4] * 100;
    n = mc[4];
    cout << n << "\n";

}

Thanks, that works.

So you need the & in int& operator[]... in order to be able to alter, but not to access, as you can only alter if it returns a reference; took me a bit to understand that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.