user5692694 user5692694 - 3 months ago 8
C++ Question

class array, cast pointer in operator[]

In my library I've an array class:

template < class Type >
class Array
{
Type* array_cData;
...
Type& operator[] (llint Index)
{
if (Index >= 0 && Index < array_iCount && Exist())
return array_cData[Index];
}
};


And that's nice, but if I've generated in the stack the class like:

Array<NString>* space = new Array<NString>(strList->toArray());
checkup("NString split", (*space)[0] == "Hello" && (*space)[1] == "world");
//I must get the object pointed by space and after use the operator[]


So my question is: I can get the object in array_cData without specify object pointed like this:

Array<NString>* space = new Array<NString>(strList->toArray());
checkup("NString split", space[0] == "Hello" && space[1] == "world");


Thanks in advance! :3

-Nobel3D

Answer

The idiomatic way is to not have pointer:

Array<NString> space{strList->toArray()};
checkup("NString split", space[0] == "Hello" && space[1] == "world");

with pointer, you have to dereference it in some way

Array<NString> spacePtr = // ...
spacePtr->operator[](0); // classical for non operator method
(*spacePtr)[0]; // classical for operator method
spacePtr[0][0]; // abuse of the fact that a[0] is *(a + 0)

 auto& spaceRef = *spacePtr;
 spaceRef[0];
Comments