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 ....
Code:
template<class T>
class arreglo
{
private:
T *A;
int length;
int top;
public:
arreglo (int inilength);
~arreglo();
insert (T data);
expand (int inc);
int &operator[](int index); //HERE IS ThE FUNC
};
#include <iostream.h>
/*********************************/
template<class T>
arreglo<T>::arreglo(int inilength)
{
if(inilength<2)
inilength=2;
//cout<<inilength;
length=inilength;
A=new T[length];
top=-1;
}
/*********************************/
template<class T>
arreglo<T>::~arreglo()
{
delete [] A;
}
/***********************************************************/
template<class T>
arreglo<T>::insert(T data)
{
top++;
if(top>=length)
//cout <<"expandiendo";
expand(length/2);
*(A+top)=data;
//cout<<endl<<"dato escrito"<<endl;
}
/**************************************/
template<class T>
arreglo<T>::expand(int inc)
{
T *temp;
temp=new T[length+inc];
for(int i=0; i<=length; i++)
{
*(temp+i)=*(A+i);
}
delete A ;
length=length+inc;
A=temp;
//cout<<top<<length;
}
/**************************************/
template<class T>
arreglo<T>::printarreglo()
{
cout<<endl<<"Datos en el arreglo"<<endl;
for(int i=0;i<top+1;i++)
cout<<*(A+i)<<" ";
cout<<endl;
}
/******************************************************/
template<class T>
int &arreglo<T>::operator[](int index)
{
/*if(index<0 || index>top)
{
cout<<endl<<"NO se encontro el indice "<<endl;
return -1;
}
else*/
{
cout<<endl<<"Ya lo encontre"<<endl;
return *(A+index);
}
}
/******************************************************/ HERE THE FUNCTION
void main()
{
arreglo<double> *nuevo;
nuevo = new arreglo<double>(1);
//nuevo->print();
nuevo->insert(30.2);
nuevo->insert(40.4);
nuevo->insert(50);
nuevo->printarreglo();
delete nuevo} // ADN HERE I DONT KNOW HOW TO MAKE
//THE OPERATION OVRLOAD CALL
I think i know how... try it
Code:
access to [] operator
class A
{
pulic:
T &operator [] (int index) {return 0; }
};
main()
{
A * a = new A;
int i = (*a)[2]; .
cout<<i;
}
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.