0

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]=...

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Kadence
0

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";

}
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.