1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

overloaded operators question

Discussion in 'C++' started by JRM, Dec 31, 2006.

  1. JRM

    JRM New Member

    Dec 31, 2006
    Likes Received:
    Trophy Points:
    I'm just trying to get a handle on the when and why of overloaded operators.

    I the following snippet:
    the line: T& operator[] ... is there for use in the copy constructor?

    the line : const T& operator [] ... is there for the constructor definition?

    In english, the code is instructing the compiler to return an array pointer of pType[] when encountering an array refernce from T.

    this is what enables the program to be versatile by being able to select different array types to be displayed?

    the line:
    Array<T>& Array<T>: operator=(const Array &rhs)
    is there to enable the seleted array to be passed into a template reference? Is this the only way to do it?

    template <class T >
    class Array;
    template <class T>
    ostream& operator << (ostream& , Array<T>& );
    template <class T> //declare the template and the parameter
    class Array       // the class being paramterized
            Array(int itsSize = DefaultSize);
            Array(const Array &rhs);
            ~Array() {delete [] ptype;}
            Array& operator = (const Array&);
            T& operator [] (int offset) {return ptype[offset];}
            const T& operator[] (int offset) const
            {return ptype[offset];}
            int GetSize() const {return itsSize;}
            friend ostream& operator << <> (ostream&, Array<T>&);
        private :
            T *ptype;
            int itsSize;
    template <class T >
    ostream& operator << (ostream& output, Array<T>& theArray)
        for (int i = 0; i < theArray.itsSize; i++)
          output << "[" << i << "]" << theArray[i] <<endl;
        return output;
    //implementations follow...
    //implement the constructor
    template <class T>
    Array<T>::Array(int size):
        ptype = new T[size];
        //the constructors of the type created
        //should be of default value
    //copy constructor
    template <class T>
    Array<T>::Array(const Array &rhs)
        itsSize =rhs.GetSize();
        ptype = new T[itsSize];
        for (int i=0; i<itsSize; i++)
            ptype[i] = rhs[i];
    template <class T>
    Array<T>& Array<T>::operator=(const Array &rhs)
        if (this == &rhs)
            return *this;
        delete [] ptype;
        itsSize = rhs.GetSize();
        ptype = new T[itsSize];
        for (int i =0; i<itsSize; i++)
            ptype[i] =rhs[i];
        return *this;

Share This Page