类模板中的友元声明

template <class ElemType>
class TreeNode
{
public :
    ......
    template <class T> void SwapLR (TreeNode <T>* t);
private:
    ......
};


    类模板中的友元声明还是有点讲究的。

    最初的代码如下所示:

template <class ElemType>
class TreeNode
{
public :
    ......
    friend void SwapLR (TreeNode <ElemType>* t);
private :
    TreeNode <ElemType>* left, *right;
};


    在codeblocks下面写的,用gcc编译,出现如下警告和错误:

warning: friend declaration 'void SwapLR (TreeNode<ElemType>*)'declares a non-template function|

note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) |

error: 'TreeNode<char>* TreeNode<char>::left' is private within this context

error: 'TreeNode<char>* TreeNode<char>::right' is private within this context

    后来看了《C++ Primer 特别版》的第16章“类模板中的友元声明”才知道怎么回事。第一次修改如下:

template <class ElemType>
class TreeNode
{
public:
    ......
    template <class ElemType> friend void SwapLR (TreeNode <ElemType>* t);
private:
    ......
};

    编译一下,还是有错误:

error: declaration of 'class ElemType' shadows template parm 'class ElemType'|

    好吧,再次修改:

template <class ElemType>
class TreeNode
{
public :
    ......
    template <class T> friend void SwapLR (TreeNode <T>* t);
private :
    ......
};

    相信你已经看出来了,没错,就是把友元声明时使用的模板声明中的ElemType类型换成T类型,从而避免shadow错误。

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值