模板類的 友元模板函數
?
123456789101112131415161718192021222324252627282930313233343536#include<iostream>
#include<string>
using
namespace
std;
?template
<
class
T>
class
Test;
template
<
class
T> ostream& operator<<(ostream& out,
const
Test<T> &obj);
template
<
class
T>
class
Test
{
private
:
????
int
num;
public
:
????
Test(
int
n=0)
????
{
????????
num = n;
????
}
????
Test(
const
Test <T> ©)
????
{
????????
num = copy.num;
????
}
????
//'<<'后面加上'<>'表明這個函數是個函數模板
????
friend
ostream& operator<< <>(ostream& out,
const
Test<T> &obj);
};
?template
<
class
T> ostream& operator<<(ostream& out,
const
Test<T> &obj)
{
????
cout << obj.num << endl;
????
return
out;
}
?
?int
main()
{
????
Test<
int
> t(2);
????
cout << t << endl;
????
getchar
();
????
return
0;
}
?
1)需要注意的是,template<class T>究竟哪里應該出現,哪里不應該出現。
2)需要重點注意的是添加注釋的行,
1: friend ostream & operator << <>( ostream & out , const Test < T > & obj );此行不可也寫成,
1: friend template < class T > ostream & operator << <>( ostream & out , const Test < T > & obj );寫成這樣也不可,
1: friend template < class T > ostream & operator <<( ostream & out , const Test < T > & obj );總之,唯一正確的寫法就是代碼段中的寫法。<>也必不可少,其實<>有兩重意思,一是,表明此友元函數是函數模板;二是,此模板使用的模板類型參數為當前模板類的類型參數class T。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
