根据我对好友函数的了解,这应该是可行的。我不知道是怎么回事。
在我的代码中我定义了一个类
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“关键字的用法,但找不到问题所在。
此实现是否因模板而遵循不同的规则
我还将<<和>>重写为移位操作符,但这也没什么关系,因为它们有不同的参数;
发布于 2014-08-09 17:54:45
使用警告up,您将拥有:
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 */
}Live example
发布于 2014-08-09 18:06:49
我想你想要的是:
template < class IType = unsigned int >
class BitArray {
template<class> friend ostream& operator<<(ostream&, const BitArray&);
template<class> friend istream& operator>>(istream&, BitArray&);
};您的BitArray声明告诉编译器查找非模板化的operator<<和operator>>
https://stackoverflow.com/questions/25217252
复制相似问题