首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模板类中的friend operator<<

模板类中的friend operator<<
EN

Stack Overflow用户
提问于 2014-08-09 17:47:12
回答 2查看 556关注 0票数 1

根据我对好友函数的了解,这应该是可行的。我不知道是怎么回事。

在我的代码中我定义了一个类

代码语言:javascript
复制
template < class IType = unsigned int >
class BitArray {
    ...
    friend ostream& operator<<(ostream&, const BitArray&);
    friend istream& operator>>(istream&, BitArray&);
    ...
}

然后在同一个头文件中

代码语言:javascript
复制
template < class IType >
ostream& operator<<(ostream& os, const BitArray<IType>& that)
{
    ...
}

template < class IType >
istream& operator>>(istream& is, BitArray<IType>& that)
{
    ...
}

它给了我

代码语言:javascript
复制
error LNK2019: unresolved external symbol

当我尝试编译的时候。

我已经重读和重写了六次,并检查了"friend“关键字的用法,但找不到问题所在。

此实现是否因模板而遵循不同的规则

我还将<<和>>重写为移位操作符,但这也没什么关系,因为它们有不同的参数;

EN

回答 2

Stack Overflow用户

发布于 2014-08-09 17:54:45

使用警告up,您将拥有:

代码语言:javascript
复制
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)

因此,在此之前声明模板函数:

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2014-08-09 18:06:49

我想你想要的是:

代码语言:javascript
复制
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>>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25217252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档