(* It's me]?

I overloaded the [] operator in my class. Is there a better way to call this function from my class other than (*this)[i] ?

+1
source share
6 answers

add a function to (size_t i) and use this function

EDIT
if you actively use stl, avoid semantic inconsistency: in std::vector operator[] it is not checked whether the index is valid, but in (..) it can throw an exception std::out_of_range . I think that in a project with more stl, similar behavior will be expected from your class.
This name may not be suitable for this function.

+8
source

Well, you can use "operator [] (i)".

+8
source

I do not like it, but clearly:

 this->operator[](i) 

If you find that you need to do this a lot, create an At () function that does exactly what the [] operator does. Then you can say:

 this->At(i) 
+6
source

This could be a reasonable compromise:

 T& me = *this; // ... me[i]; 
+6
source

Since you are undertaking something from your own class, why not just use a private function named as you see fit:

 class MyClass { private: SomeType& Item(int index) { /* return a value */ } public: SomeType& operator[](int index) { return Item(index); } void SomeFunction(void); } void myClass::SomeFunction(void) { SomeType localVar = Item(42); // internal access } int main(int argCount, char ** argList) { MyClass myClass; SomeType x; x = myClass[42]; // external access return 0; } 
+4
source

this->[i] does not even compile. The only other option is this->operator[](i) .

0
source

All Articles