tags:

views:

453

answers:

6
+1  Q: 

(*this)[i] ?

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

+7  A: 

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

Fred Larson
+6  A: 

Not nice, but explicit:

this->operator[](i)

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

this->At(i)
anon
I'm not sure I'd advocate adding an 'at' that does *exactly* the same as operator[]. It departs from the precedent set by the standard.
Charles Bailey
OK, call it At()
anon
I wouldn't recommend duplicating the code (I doubt that's what Neil is suggesting), but there wouldn't be anything wrong with having operator[]() call the at() or At().
Fred Larson
You don't need to put "this->" in front of a method call.
j_random_hacker
+8  A: 

add function at(size_t i) and use this function

EDIT
if you actively using stl avoid semantic inconsistence: in std::vector operator[] does not check if index is valid, but at(..) check and could throw std::out_of_range exception. I think in project with more stl similar behavior will expected from your class.
Maybe this name is not best one for this function.

bb
I suppose that's about the best I can do then, thanks.
Mark
A: 

this->[i] doesn't even compile. The only other option is this->operator[](i).

MSN
You don't need "this->" in front of a method call.
j_random_hacker
+6  A: 

This might be a reasonable compromise:

T& me = *this;

// ...

me[i];
Michael Burr
Would be nice if C++ had a built in special type for *this. PHP has "self" but that's not quite the same either. Anyway, thanks for the suggestion :)
Mark
According to Stroustup, 'this' probably would have been a reference except that references came along too late in the evolution of C++.
Michael Burr
Damn shame he didn't go back and rewrite everything to be reference-centric when that happened. It would have been a far better language.
T.E.D.
+4  A: 

Since you are acessing something from within 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;
}
e.James
That example is a little overkill for your point, but thanks :) +1 for effort
Mark
Haha true. I just didn't know where to stop : )
e.James