源代码:
#include <fstream>
using namespace std;
ifstream fin("abc.txt");
template <class T>
class abc{
T data;
public:
friend void operator>>( ifstream &, abc<T> & );
};
template <class T>
void operator>>( ifstream &fin, abc<T> &t )
{
fin >> t.data;
}
int main()
{
abc<int> t;
fin >> t;
return 0;
}
用g++编译,但编译警告operator>>后要有<T>,连接错误:找不到operator>>函数。
这样写很好啊,不会编译出错吧?·
template <class T>
class abc{
T data;
public:
friend void operator>> <T> ( ifstream &, abc<T> & ); //声明必须指定模板参数
};
g++? 我kao, 那不知道了。 可能你加个const什么的就可以了吧?
Linux对语言要求很严格的。
去掉名称空间试试..
#include <fstream.h>
template <class Type>
class QueueItem {
friend class foobar<Type>;
friend void foo<Type>( QueueItem<Type> );
friend void Queue<Type>::bar();
// ...
};
foo()的友元声明的语法看起来或许令人吃惊
friend void foo<Type>( QueueItem<Type> );
函数名后面紧跟着显式的模板实参表foo<type> 这种语法可用来指定该友元声明所引
用的函数模板foo()的实例如果省略了显式的模板实参如下所示
friend void foo( QueueItem<Type> );
则友元声明会被解释为引用了一个非模板函数且该函数的参数类型是类模板
http://www.vckbase.com/document/viewdoc/?id=501
friend void operator>><>(ifstream&, abc<T>&);你试试这个
#include <fstream>
using namespace std;
ifstream fin("abc.txt");
template <class T>
class abc{
T data;
public:
template <class U>
friend ifstream& operator>>( ifstream &, abc<U> & );
};
template <class U>
ifstream& operator>>( ifstream &fin, abc<U> &t )
{
fin >> t.data;
return fin;
}
int main()
{
abc<int> t;
fin >> t;
return 0;
}