我正在学习如何使用模板以及如何重载运算符。我设法超载operator[]
,但我遇到了超载operator+
和operator=
的问题。这里是我的代码:重载运算符'='和'+'
template <class T>
class A
{
public:
//...
friend A<T>& A<T>::operator+ (A<T>&, const A<T>&);
friend A<T>& A<T>::operator= (A<T>&, const A<T>&);
};
template<class T> A<T>& A<T>::operator+ (A<T>& left, const A<T>& right)
{
//some functions
return left;
}
template<class T> A<T>& A<T>::operator= (A<T>& left, const A<T>& right)
{
//some functions
return left;
}
Whenver我尝试编译,我得到这些错误:
'+': is not a member of 'A<T>'
'=': is not a member of 'A<T>'
'operator =' must be a non-static member
我在做什么错?
编辑:
我已经成功地更新代码:
template <class T>
class A
{
public:
//...
A<T> operator+ (A<T>);
A<T> operator= (A<T>, const A<T>);
};
template<class T> A<T> A<T>::operator+ (A<T> right)
{
//some functions
return *this;
}
template<class T> A<T> operator= (A<T> right)
{
//some functions
return *this;
}
貌似operator+
作品现在很好,但是编译器会发出此错误:
'operator=' must be a non static member
为什么它是一个静态成员,我该如何解决它?
在函数定义中删除'一个 ::'范围。 –
对不起,我忘了。模板参数不会被“继承”到“朋友”声明中。您必须将它们声明为模板朋友A &operator +(A &,const A &);' –
您确定吗?我得到了现在编译器的内部错误:P 没关系,它现在仍然产生'不成员'的错误:/ – Executor1909