I’ve overloaded the [] (square brackets) operator of a simple class in C++ to return an integer from an array. I now what to reuse this overloaded operator in a member function. I am having trouble implementing this, as using *this[ i ] apparently does not work, although I can reference the operator directly:
int & A::operator [] (size_t i)
{
return ints[ i ];
}
...
int A::getVal ( size_t i) const
{
// Does not work
return *this[ i ];
// Does work
// return operator []( i );
}
Why is it that dereferencing the pointer this and using the operator [] results in a compile error but calling the operator directly works?
I get the following error compiling:
cannot convert from ‘const Array’ to ‘char’
Thank you for any input.
It doesn’t. But you have to spell it right. Change
to
As originally written, it applies
[i]tothis, then dereferences the result.