Why does it require to be a member function of a class for its operation and is good to return a reference to private member?
class X
{
public:
int& operator[] (const size_t);
const int &operator[] (const size_t) const;
private:
static std::vector<int> data;
};
int v[] = {0, 1, 2, 3, 4, 5};
std::vector<int> X::data(v, v+6);
int& X::operator[] (const size_t index)
{
return data[index];
}
const int& X::operator[] (const size_t index) const
{
return data[index];
}
As to why is it required to have [] as a member, you can read this question (by yours sincerely). Seems it's just the way it is with no really really convincing explanation.
As to why return reference? Because you want to provide a way not only to read, but also (for non-const objects) to modify the data. If the return weren't a reference (or some proxyr)
v[i] = 4;
wouldn't work.
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With