[英]friend operator<< in template class
据我了解的朋友功能,这应该工作。 我不确定发生了什么。
在我的代码中,我定义了一个类
template < class IType = unsigned int >
class BitArray {
...
friend ostream& operator<<(ostream&, const BitArray&);
friend istream& operator>>(istream&, BitArray&);
...
}
然后在同一个头文件中
template < class IType >
ostream& operator<<(ostream& os, const BitArray<IType>& that)
{
...
}
template < class IType >
istream& operator>>(istream& is, BitArray<IType>& that)
{
...
}
这给了我
error LNK2019: unresolved external symbol
当我尝试编译时。
我已经重新阅读并重新编写了六遍,并查看了“ friend”关键字的使用,但找不到问题所在。
由于模板,此实现是否遵循不同的规则
我也重写了<<和>>作为移位运算符,但同样不要紧,因为它们具有不同的参数。
发出警告后,您将:
warning: friend declaration 'std::ostream& operator<<(std::ostream&, const BitArray<IType>&)' declares a non-template function [-Wnon-template-friend]
note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
因此,在声明模板函数之前:
template <class IType> class BitArray;
template <class IType> std::ostream& operator<<(std::ostream&, const BitArray<IType>&);
template <class IType> std::istream& operator>>(std::istream&, BitArray<IType>&);
template < class IType = unsigned int >
class BitArray {
friend std::ostream& operator<< <>(std::ostream&, const BitArray&);
friend std::istream& operator>> <>(std::istream&, BitArray&);
};
template <class IType>
std::ostream& operator<<(std::ostream& os, const BitArray<IType>& b)
{
/* Your implementation */
}
我想你想要这个:
template < class IType = unsigned int >
class BitArray {
template<class> friend ostream& operator<<(ostream&, const BitArray&);
template<class> friend istream& operator>>(istream&, BitArray&);
};
您的BitArray声明告诉编译器寻找非模板运算符<<和operator >>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.