我正在尝试在模板类中重载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;
}我也试过了:
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;
}但是我仍然得到这个错误:
error C2801: 'operator =' must be a non-static member发布于 2012-06-24 03:38:38
错误运算符:‘C2801 =’必须是非静态成员
粗体的词是这里的关键。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;
}尽管我认为在那里使用该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;
}说明:您通常不希望以这种方式将 Type<V>分配给Type<T>;如果您必须这样做,那么这可能是糟糕设计的标志。
发布于 2012-06-24 03:44:01
标准上说
12.8复制和移动类对象 class.copy
..。
17用户声明的复制赋值运算符X::operator=是类X的非静态非模板成员函数,它只有一个参数,类型为X、X&、常量X&、易失性X&或常量易失性X&。
好友函数不能满足这些要求。它必须是成员函数。
为了解决这只是“普通”赋值,而不是复制赋值的评论,让我们从标准中添加另一个引用:
13.5.3 Assignment over.ass
赋值运算符应该由只有一个参数的非静态成员函数实现。
在标准语言中,“应当”不会留下任何其他选项。
发布于 2012-06-24 03:49:00
您混合了朋友和成员的声明和定义:在第一个示例中,您将operator=声明为朋友,但将其定义为类成员。在第二个示例中,您将operator=声明为成员,但尝试将其定义为非成员。您的operator=必须是成员(请参阅this question为什么),并且您可以执行以下操作:
template <class T>
class Matrice
{
T m,n;
public:
Matrice<T>& operator=(Matrice<T> &);
};
template <class T>
Matrice<T>& Matrice<T>::operator=(Matrice<T> &M)
{
/*...*/
return *this;
}https://stackoverflow.com/questions/11172389
复制相似问题