【发布时间】:2017-04-07 20:07:16
【问题描述】:
我正在学习如何使用模板以及如何重载运算符。我已经设法重载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;
}
每当我尝试编译时,我都会收到这些错误:
'+': 不是'A
'的成员 '=':不是'A
'的成员 'operator =' 必须是非静态成员
我做错了什么?
编辑:
我已经设法更新了代码:
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=' 必须是非静态成员
为什么它是静态成员,我该如何修复它?
【问题讨论】:
-
删除函数定义中的
A<T>::范围。 -
对不起,我忘了。模板参数不是 “继承” 到
friend声明。您必须将它们声明为template<typename U> friend A<U>& operator+ (A<U>&, const A<U>&); -
你确定吗?我现在得到编译器的内部错误:P 没关系,它现在仍然产生“非成员”错误:/
-
可以先放
friend,但我对此有100%的把握。
标签: c++ operators overloading