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

{
7
public:
8
// 構造函數
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
// 友元模板的實現
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都不能編譯通過,報連接錯誤,或者報模板函數是一個普通非模板類,或者非模板函數。
于是翻開C++ Primer,在16.4節有詳細的說明,
1.對于一個特化的類,聲明一個友元模板必須對友元模板授予類的一個實例。
2.對特定實例化的友元關系時,必須在可以用于友元聲明之前聲明類或函數。
所以下面是修改后的代碼
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
// 構造函數
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
// 特化時,<Type,dim> 省略為<>
23
friend ostream & operator << <>(ostream & out , const DTest<Type,dim> & data);
24
25
private:
26
Type _cords[dim];
27
};
28
29
// 友元模板的實現
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. 常見的幾種內存泄漏
1.分配空間未釋放
2.嵌套對象指針未釋放,
比如,一個類中包含另一個類的指針,在初始化的時候分配空間,缺沒有在析構函數釋放他。
3.釋放一個對象數組的時候沒有使用[] ,
delete m_pObj; 只是釋放第一個&m_pObj[0] 對象,應該使用delete [] m_pObj;
4.出現淺拷貝現象
5.返回一個動態分配的對象,其實可以看【effective c++】 的條款23: 必須返回一個對象時不要試圖返回一個引用
先總結這些,以后慢慢記錄我的學習筆記。