Overload [ ] in a class template with a pointer

This is a discussion on Overload [ ] in a class template with a pointer within the C++ Programming forums, part of the General Programming Boards category; Hi well i have a big prob , i wonder if u can help me... to solve it, look i ...

Overload [ ] in a class template with a pointer

Hi well i have a big prob , i wonder if u can help me... to solve it, look i have to do , a templete with a few operations with one array , so i have the , inserrt , the erase, search etc.. so , in the main i use a ponter to make the array , so my prob is that i need to overlaod de operator [ ] but i dont know how i ll call form main i have the function to overload it but... i dont how ,i will send the code ....

Well first off void main is wrong. It is int main(). Second off why use that strange way of adressing the data. You can use it just like an array since you allocated with new []. Here is a quick example.

You don't call the function like a function it is operator overloading so you would use it like you would the regular way. neuvo[theIndexYouWant] and that will give you the goods at the specified index.

so in that the operator returns me the data that is on the index in the array , but i have a little problem if i leave the if that check if the index is 0-top range this error comes rror C2440: 'return' : cannot convert from 'const int' to 'double &' cout<<(*nuevo)[-1]; so if i omitt the if clause everithing is good , but i need to have a return if the range is over the boundaries soo :S:S ... ????

tnks , for the help but....

i know that it is not the best way to doit, and i undertand ur comment but this is for a school proyect where the tich told us to make thath way , so , he needs to tha main goes in that way , like insert the data in tha main , and , also have the search to fiand a data , or a print function that prints all the array but , y need to overload de [ ] for return me the data on the index that i give.

Not really. You only need a return statement for the function as a whole. Since you can't return an int or a T, unless T is an int, you'll have to come up with something else. Why not display an error statement to the user if the index is out of range, and have them input an index that is within range and keep doing that until they do put enter an index that is within range, and then return the value indicated by the index as you already do. That way you won't need a return value from within the if statement that is a different type from T, the error statement will go away, and the user will be able to get the data they really want, without the program crashing or overreaching the boundaries of the array, etc.

Code:

while index not in valid range
output statement to user
get new index from user
return value using index that is gauranteed to be within range