LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1354|回复: 1

g++编译c++模板友元类问题

[复制链接]
发表于 2009-3-8 21:56:17 | 显示全部楼层 |阅读模式
在tmeplate <class T>中声明一个友元:
friend ostream & operator<<(ostream&,Array<T>&);
这一句在g++中编译通不过:以下是出错信息:
4.cpp:38: 警告: 友元声明‘std:stream& operator<<(std:stream&, Array<T>&)’声明了一个非模板函数
4.cpp:38: 警告: (如果这不是您原来的想法,请确定此函数模板已经声明过,并在这里的函数名后面添加 <>) -Wno-non-template-friend 禁用此警告
/tmp/ccnDvlHH.o: In function `main':
4.cpp.text+0x29e): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Array<int>&)'
collect2: ld 返回 1



然后在google了一下,在国外的网站上看了看,没看懂,有人说把那句改为
friend ostream & operator<< <>(ostream&,Array<T>&);
但还是出错了,以下是出错信息:
4.cpp: In instantiation of ‘Array<int>’:
4.cpp:82:   instantiated from here
4.cpp:38: 错误: 模板标识符‘operator<< <>’(属于‘std::basic_ostream<char, std::char_traits<char> >& operator<<(std::basic_ostream<char, std::char_traits<char> >&, Array<int>&)’)不匹配任何模板声明


望知道的朋友指点.谢过!
 楼主| 发表于 2009-3-12 22:44:14 | 显示全部楼层

问题已解决.

我在csdn上找一了一些解答,第一种办法是在前面加
template <class T> class Array;
template <class T> ostream& operator <<(ostream& out,const Array<T>& a);

第二种方法,就是直接在模板中实现在,即:
template <class T>
class Array{
public:
            ........something......
            friend ostream& operator<< (ostream& out,Array<T>&rhs){
                       .......something.....
            }
};


最后我想知道是什么原因这样做,我知道我很菜,请高手一定给要说一下.
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表