Ramyad
Ramyad

Reputation: 107

overloading operators in class template

I write a class template, but operators work only when two types are same. I do not know how to define to types in header file and cpp file. This is my code:

header file:

ArrayList& operator=(ArrayList const&);

cpp file:

template <class T>
ArrayList<T>& ArrayList<T>::operator=(ArrayList<T> const& other) {
    if (this != &other) {
        delete [] Array;
        Array = new T [other.lenght];
        lenght = other.lenght;
        std::copy(other.Array, other.Array+lenght, Array);
    }
    return *this;
}

if I define a and b as int, a=b works. but if I define a as a char, a=b does not work. how to solve this?

EDITED::

As Barry said, we must change the syntax. And I must change my instantiations at the end of the .cpp file (I am using separate .h and .cpp file). But the problem is from this part

 if (this != &other) {
    delete [] Array;
    Array = new T [other.lenght];
    lenght = other.lenght;
    std::copy(other.Array, other.Array+lenght, Array);
}

but I do not know where is the problem, if I comment above, everything works good, but...

I got these errors:

error C2440: '!=' : cannot convert from 'const ArrayList *' to 'ArrayList *const '

error C2248: 'ArrayList::lenght' : cannot access private member declared in class 'ArrayList' (3 times)

Upvotes: 2

Views: 513

Answers (1)

Barry
Barry

Reputation: 304142

In your header, instead of:

ArrayList& operator=(ArrayList const&);

Make it

template <typename U>
ArrayList& operator=(ArrayList<U> const&);

That should accept any kind of U on the right hand side. Similarly, the cpp file should use this awesome construction:

template <typename T>
template <typename U>
ArrayList<T>& ArrayList<T>::operator=(ArrayList<U> const& other) {
    // clearly uninteresting details here
    return *this;
}

Upvotes: 6

Related Questions