Thread: Overload [ ] in a class template with a pointer

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    12

    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

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    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.
    Code:
    #include <iostream>
    
    template <class T>
    class test
    {
        public:
            test()
            {
                this->testSize = 0;
                data = new T[1]; //just to allocate one and make using delete [] ok :)
            }
            test(const T &data) //copy constuctor for adding one T
            {
                this->data = new T[1];
                this->data[0] = data; 
                this->testSize = 1;
            }
            void push_back(const T &data) //Add some T to the end.
            {                
                T *temp = new T[this->testSize]; //creating a temp to hold the old contents
                for(int i = 0; i < this->testSize; i++)
                {
                    temp[i] = this->data[i];
                }
                delete [] this->data; //freeing the old memory
                this->data = new T[this->testSize + 1];  //re-allocating some new stuff
                for(int i = 0; i < this->testSize; i++)
                {
                    this->data[i] = temp[i];
                }
                this->data[this->testSize] = data;                    
                this->testSize++;
                delete [] temp;
            }                    
            const T &operator [](int index) const 
            {
                return this->data[index]; //this returns non modifyable data
            }
            const int &size()
            {
                return this->testSize; //returning the size of the thingy
            }
            ~test()
            {
                delete [] data; //freeing the memory
            }
        private:
            T *data;    //the "goods"
            int testSize;  //how many items are in here 
    };
    
    int main()
    {
        test <int>mainTest(1);
        for(int i = 0; i < 10; i++)
        {
            mainTest.push_back(rand() % 50);
        }
        for(int i = 0; i < mainTest.size(); i++)
        {
            std::cout<<mainTest[i]<<std::endl;
        }        
        std::cin.get();
    }
    I don't know if this is all good since I kinda whipped it up but I should give you a clue.
    Woop?

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    12

    Tnks , but...

    yeah , kindda... but , the thing is that is a proyect for school so i need to doit like that so i dont know how to make de call in main to the olverload function of the operator

  4. #4
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    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.
    Woop?

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    12

    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;
    }

  6. #6
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    That will return 0 no matter what the index is.
    Code:
    const T &operator [](int index) const 
    {
        return this->data[index]; //this returns non modifyable data at the specified index
    }
    You do know how to access an regular array right?
    This is doing the same thing but it is accessing the data inside the class and returning the result.
    Woop?

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    12

    ...

    yes , well my real overload function is this
    Code:
    template<class T>
    T &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);
       }
    }
    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 ... ????

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    12

    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.

  9. #9
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    >but i need to have a return if the range is over the boundaries soo

    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
    You're only born perfect.

  10. #10
    Registered User
    Join Date
    Jun 2004
    Posts
    722
    if the index is out of boundaries you have some choices:
    • ignore the index and leave it for the programmer to check
    • throw an exception
    • return a default value //for reading only

    don't use const or you'll limit the operator to read only

  11. #11
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    >don't use const or you'll limit the operator to read only
    And is this always a bad thing?
    Woop?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. template function v.s. template class
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 12-13-2007, 01:46 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Instantiating a template class
    By NullS in forum C++ Programming
    Replies: 11
    Last Post: 02-23-2005, 10:04 AM
  5. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM