A.特化類的友元模板函數(shù)的操作符重載
最近寫一測(cè)試代碼關(guān)于特化類的友元模板函數(shù)的操作符重載遇到一問(wèn)題。
先貼一個(gè)錯(cuò)誤代碼:
1
#pragma region 類DTest信息
2
3
// 聲明一個(gè)類
4
template<class Type , int dim>
5
class DTest
6

{
7
public:
8
// 構(gòu)造函數(shù)
9
DTest()
10
{
11
memset(_cords,0,sizeof(_cords));
12
}
13
DTest(Type cord[dim])
14
{
15
memcpy(_cords,cord,sizeof(cord));
16
}
17
18
// 友元模板
19
friend ostream & operator << (ostream & out , const DTest<Type,dim> & data);
20
21
private:
22
Type _cords[dim];
23
};
24
// 友元模板的實(shí)現(xiàn)
25
template<class Type, int dim>
26
ostream & operator << (ostream & out , const DTest<Type,dim> & data)
27

{
28
for(int i = 0 ; i < dim-1 ; i++)
29
out << data._cords[i] <<" ";
30
31
out <<endl;
32
return out;
33
}
34
35
#pragma endregion
用devc++,Vs2005,vc2008都不能編譯通過(guò),報(bào)連接錯(cuò)誤,或者報(bào)模板函數(shù)是一個(gè)普通非模板類,或者非模板函數(shù)。
于是翻開C++ Primer,在16.4節(jié)有詳細(xì)的說(shuō)明,
1.對(duì)于一個(gè)特化的類,聲明一個(gè)友元模板必須對(duì)友元模板授予類的一個(gè)實(shí)例。
2.對(duì)特定實(shí)例化的友元關(guān)系時(shí),必須在可以用于友元聲明之前聲明類或函數(shù)。
所以下面是修改后的代碼
1
template<class Type , int dim>
2
class DTest;
3
template<class Type , int dim>
4
ostream & operator << (ostream &out ,const DTest<Type,dim> &sess);
5
6
7
#pragma region 類DTest信息
8
template<class Type , int dim>
9
class DTest
10

{
11
public:
12
// 構(gòu)造函數(shù)
13
DTest()
14
{
15
memset(_cords,0,sizeof(_cords));
16
}
17
DTest(Type cord[dim])
18
{
19
memcpy(_cords,cord,sizeof(cord));
20
}
21
22
// 特化時(shí),<Type,dim> 省略為<>
23
friend ostream & operator << <>(ostream & out , const DTest<Type,dim> & data);
24
25
private:
26
Type _cords[dim];
27
};
28
29
// 友元模板的實(shí)現(xiàn)
30
template<class Type, int dim>
31
ostream & operator << (ostream & out , const DTest<Type,dim> & data)
32

{
33
for(int i = 0 ; i < dim-1 ; i++)
34
out << data._cords[i] <<" ";
35
36
out <<endl;
37
return out;
38
}
39
#pragma endregion
B. 常見的幾種內(nèi)存泄漏
1.分配空間未釋放
2.嵌套對(duì)象指針未釋放,
比如,一個(gè)類中包含另一個(gè)類的指針,在初始化的時(shí)候分配空間,缺沒(méi)有在析構(gòu)函數(shù)釋放他。
3.釋放一個(gè)對(duì)象數(shù)組的時(shí)候沒(méi)有使用[] ,
delete m_pObj; 只是釋放第一個(gè)&m_pObj[0] 對(duì)象,應(yīng)該使用delete [] m_pObj;
4.出現(xiàn)淺拷貝現(xiàn)象
5.返回一個(gè)動(dòng)態(tài)分配的對(duì)象,其實(shí)可以看【effective c++】 的條款23: 必須返回一個(gè)對(duì)象時(shí)不要試圖返回一個(gè)引用
先總結(jié)這些,以后慢慢記錄我的學(xué)習(xí)筆記。