C++错误C2801:'operator ='必须是非静态成员

Iul*_*rei 2 c++ templates overloading class operator-keyword

我试图operator=在模板类中重载.

我有这个模板类:

template <class T>
class Matrice
{
    T m,n;
public:
    template <class V>
    friend Matrice<V>& operator=(const Matrice<V> &);
};

template <class T>
Matrice<T>& Matrice<T>::operator=(const Matrice<T> &M)
{
    /*...*/
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

template <class T>
class Matrice
{
    T m,n;
public:
    template <class V>
    Matrice<V>& operator=(Matrice<V> &);
};

template <class T>
Matrice<T>& operator=(Matrice<T> &M)
{
    /*...*/
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

但我仍然得到这个错误:

error C2801: 'operator =' must be a non-static member
Run Code Online (Sandbox Code Playgroud)

Gri*_*wes 5

错误C2801:'operator ='必须是非静态成员

粗体字是关键.friend不是会员; 这是一个朋友.删除该friend关键字并operator=视为成员:

语法上合适的版本是:

template <class T>
class Matrice
{
    T m,n;
public:
    template <class V>
    Matrice<V>& operator=(const Matrice<V> &);
};

template <class T>
template <class V>
Matrice<V>& Matrice<T>::operator=(const Matrice<V> &M)
{
    /*...*/
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

虽然我认为在template <class V>那里使用它是错误的; 这个版本正确的版本将是

template <class T>
class Matrice
{
    T m,n;
public:
    Matrice<T>& operator=(const Matrice<T> &);
};

template <class T>
Matrice<T>& Matrice<T>::operator=(const Matrice<T> &M)
{
    /*...*/
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

说明:您不一般要分配 Type<V>Type<T>这种方式; 如果你必须,那么它可能是糟糕设计的标志.