I overloaded the [] operator in my class. Is there a nicer way to call this function from within my class other than (*this)[i]
?
views:
453answers:
6
+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
2009-03-31 16:59:18
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
2009-03-31 17:05:17
OK, call it At()
anon
2009-03-31 17:08:06
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
2009-03-31 17:13:45
You don't need to put "this->" in front of a method call.
j_random_hacker
2009-04-01 02:02:13
+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
2009-03-31 17:00:10
A:
this->[i]
doesn't even compile. The only other option is this->operator[](i)
.
MSN
2009-03-31 17:04:08
+6
A:
This might be a reasonable compromise:
T& me = *this;
// ...
me[i];
Michael Burr
2009-03-31 17:05:31
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
2009-03-31 17:22:47
According to Stroustup, 'this' probably would have been a reference except that references came along too late in the evolution of C++.
Michael Burr
2009-03-31 17:30:35
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.
2009-03-31 17:32:46
+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
2009-03-31 17:14:55