猫咪的晴天

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错误。

天才是百分之一的灵感加上百分之久十久的努力

猫咪的晴天

相关文章:

你感兴趣的文章:

标签云: