在类模板中重载运算符

Ram*_*yad 2 c++ templates overloading class operator-overloading

我编写了一个类模板,但只有当两种类型相同时,运算符才能工作.我不知道如何定义头文件和cpp文件中的类型.这是我的代码:

头文件:

ArrayList& operator=(ArrayList const&);
Run Code Online (Sandbox Code Playgroud)

cpp文件:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果我将a和b定义为int,则a = b有效.但如果我将a定义为char,则a = b不起作用.怎么解决这个?

EDITED ::

正如巴里所说,我们必须改变语法.我必须在.cpp文件的末尾更改我的实例化(我使用单独的.h和.cpp文件).但问题出在这一部分

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

但我不知道问题在哪里,如果我在上面评论,一切都很好,但......

我收到了这些错误:

错误C2440:'!=':无法从'const ArrayList*'转换为'ArrayList*const'

错误C2248:'ArrayList :: lenght':无法访问类'ArrayList'中声明的私有成员(3次)

Bar*_*rry 6

在标题中,而不是:

ArrayList& operator=(ArrayList const&);
Run Code Online (Sandbox Code Playgroud)

做了

template <typename U>
ArrayList& operator=(ArrayList<U> const&);
Run Code Online (Sandbox Code Playgroud)

那应该接受右手边的任何一种U. 同样,cpp文件应该使用这个很棒的结构:

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