可能重复:
为模板类重载友元运算符<<
我正在尝试为模板类重载 operator<<,但出现错误...
最终(固定)代码:
template<class T>
class mytype
{
T atr;
public:
mytype();
mytype(T);
mytype(mytype&);
T getAtr() const;
T& operator=(const T&);
template<class U> friend ostream& operator<<(ostream&,const mytype<U>&);
};
template<class T>
mytype<T>::mytype()
{
atr=0;
}
template<class T>
mytype<T>::mytype(T value)
{
atr=value;
}
template<class T>
mytype<T>::mytype(mytype& obj)
{
atr=obj.getAtr();
}
template<class T>
T mytype<T>::getAtr() const
{
return atr;
}
template<class T>
T& mytype<T>::operator=(const T &other)
{
atr=other.getAtr();
return *this;
}
template<class U>
ostream& operator<<(ostream& out,const mytype<U> &obj)
{
out<<obj.getAtr();
return out;
}
(全部在头文件中)
VS2012 错误:
1)
错误 1 错误 LNK2019:函数 _wmain 中引用的未解析外部符号“public: __thiscall mytype::mytype(int)”(??0?$mytype@H@@QAE@H@Z)
2)
错误 2 错误 LNK2019: 无法解析的外部符号 "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class mytype const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@ D@std@@@std@@AAV01@ABV?$mytype@H@@@Z) 在函数 _wmain 中引用
3)
错误 3 error LNK1120: 2 unresolved externals
我的代码有什么问题?