4
从“Thinking in C++ Volume 2”中的Thinking in Depth章节看到,如果您在模板类中具有友好的功能,则需要转发声明该功能。我提出这个例子来测试,overlaoding输出操作:模板和朋友
#include <iostream>
using namespace std;
/*
template<class T>
class X;
template<class T>
ostream& operator << (ostream& os, const X<T>& x);
*/
template<class T>
class X {
T t;
public:
X(T i): t(i) {}
friend ostream& operator << (ostream& os, const X<T>& x)
{
return os << x.t;
}
};
int main()
{
X<int> a(1);
cout << a;
return 0;
}
但它的工作原理没有提前声明,但后来我的< <外部类的定义测试:
friend ostream& operator << <>(ostream& os, const X<T>& x); (inside of the class)
template<class T>
ostream& operator << (ostream& os, const X<T>& x)
{
return os << x.t;
}
我不确定为什么在类中定义它不适用,是因为你必须明确说ostream操作符函数是一个模板? (使用<>)?
对不起,我感到困惑。
C++ FAQ Lite也有这方面的一章:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16 – Cubbi 2011-05-04 21:06:59
@ Cubbi:哦,所以当我定义它时在班级里面,没有必要提前申报,完美的探索,谢谢:) – Kobe 2011-05-04 21:11:36