首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于模板类中的重载运算符的友元函数

2012-02-27 
求助 关于模板类中的重载运算符的友元函数[root@localhostgenDLLst]#g++-ogenDLLst2genDLLst2.cppgenDLLst

求助 关于模板类中的重载运算符的友元函数
[root@localhost   genDLLst]#   g++   -o   genDLLst2   genDLLst2.cpp
genDLLst2.cpp:41:   warning:   friend   declaration   `std::ostream&   operator < <(std::ostream&,   const   DoublyLinkedList <T> &) '   declares   a   non-template   function
genDLLst2.cpp:41:   warning:   (if   this   is   not   what   you   intended,   make   sure   the   function   template   has   already   been   declared   and   add   <>   after   the   function   name   here)   -Wno-non-template-friend   disables   this   warning

源代码如下:
#include <iostream>
using   namespace   std;
template <typename   T>
class   DLLNode   {
public:
                DLLNode()   {
                                next   =   prev   =   0;
                }
        DLLNode(const   T&   el,   DLLNode   *n   =   0,   DLLNode   *p   =   0)   {
                info   =   el;   next   =   n;   prev   =   p;
        }
        T   info;
        DLLNode   *next,   *prev;
};
template <typename   T>
class   DoublyLinkedList   {
public:
        DoublyLinkedList()   {
                head   =   tail   =   0;
        }
        void   addToDLLTail(const   T&);
        T   deleteFromDLLTail();
                ~DoublyLinkedList()   {
                                clear();
                }
        bool   isEmpty()   const   {
                return   head   ==   0;
        }
                void   clear();
        void   setToNull()   {
                head   =   tail   =   0;
        }
        void   addInMiddle(const   T&);
        void   addToDLLHead(const   T&);
        T   deleteFromDLLHead();
        T&   firstEl();
        T*   find(const   T&)   const;
        void   run();
protected:
        DLLNode <T>   *head,   *tail;
        friend   ostream&   operator < <(ostream&,   const   DoublyLinkedList <T> &);
};
template <typename   T>
ostream&   operator < <(ostream&   out,   const   DoublyLinkedList <T> &   dll)   {


        DLLNode <T>   *tmp;
        for   (tmp   =   dll.head;   tmp   !=   0;   tmp   =   tmp-> next)
                out   < <   tmp-> info   < <   '   ';
        return   out;
}
int   main()
{
return   0;
}


[解决办法]
friend ostream& operator < <(ostream&, const DoublyLinkedList <T> &)
{
DLLNode <T> *tmp;
for (tmp = dll.head; tmp != 0; tmp = tmp-> next)
out < < tmp-> info < < ' ';
return out;
}
friend声明时就地实现。

热点排行