模板类的友元重载函数

#include <iostream>

using namespace std;



template<class T>

class Test 

{

public:

friend ostream& operator << <> (ostream& out, const Test<T>& obj);


Test(T n=0):num(n){}


Test(const Test<T>& copy)

{

num = copy.num;

}


private:

T num;

};


template<class T>

ostream& operator << <> (ostream& out, const Test<T>& obj)

{

out<<obj.num<<endl;

return out;

}


int main()

{

Test<int> t(2);

cout<<t;

return 0;

}


或者是


#include <iostream>

using namespace std;



template<class T>

class Test 

{

public:

 template<class T>

friend ostream& operator << (ostream& out, const Test<T>& obj);


Test(T n=0):num(n){}


Test(const Test<T>& copy)

{

num = copy.num;

}


private:

T num;

};


template<class T>

ostream& operator << (ostream& out, const Test<T>& obj)

{

out<<obj.num<<endl;

return out;

}


int main()

{

Test<int> t(2);

cout<<t;

return 0;

}

posted @ 2009-06-24 15:00  小 楼 一 夜 听 春 雨  阅读(270)  评论(0编辑  收藏  举报