將上一篇的動態數組的函數模板封成了類,但沒有錯誤處理等。
#include?
<
iostream
>
#include?
<
string
>
using
?
namespace
?std;
template
<
class
?T
>
class
?TDArray
{
public
:
????TDArray(
int
?rows,?
int
?cols);
????
~
TDArray();
????template
<
class
?Tt
>
?friend?ostream
&
?
operator
<<
(?ostream
&
?output,?
const
?TDArray
<
Tt
>&
?tdArray?);
????T
*
?
operator
[](
int
?rows);
private
:
????
void
?Init();
????T?
**
p;
????
int
?m_rows;
????
int
?m_cols;
}
;
template
<
class
?T
>
TDArray
<
T
>
::TDArray(
int
?rows,?
int
?cols)
{
????m_rows?
=
?rows;
????m_cols?
=
?cols;
????
//
?創建行指針
????p?
=
?
new
?T
*
[rows];
????
//
?為每一行分配空間
????
for
?(
int
?i
=
0
;?i
<
rows;?
++
i)
????
{
????????p[i]?
=
?
new
?T[cols];
????}
????
//
?初始化
????Init();
}
template
<
class
?T
>
TDArray
<
T
>
::
~
TDArray()
{
????
for
?(
int
?x
=
0
;?x
<
m_rows;?
++
x)
????
{
????????delete[]?p[x];
????}
????delete[]?p;
????p?
=
?
0
;
}
template
<
class
?T
>
inline?
void
?TDArray
<
T
>
::Init()
{
????
for
?(
int
?x
=
0
;?x
<
m_rows;?
++
x)
????
{
????????
for
?(
int
?y
=
0
;?y
<
m_cols;?
++
y)
????????
{
????????????p[x][y]?
=
?T();
????????}
????}
}
template
<
class
?T
>
ostream
&
?
operator
<<
(?ostream
&
?output,?
const
?TDArray
<
T
>&
?tdArray?)
{
????
for
?(
int
?x
=
0
;?x
<
tdArray.m_rows;?
++
x)
????
{
????????
for
?(
int
?y
=
0
;?y
<
tdArray.m_cols;?
++
y)
????????
{
????????????output?
<<
?
"
[
"
?
<<
?x?
<<
?
"
][
"
?
<<
?y?
<<
?
"
]
"
?
<<
?tdArray.p[x][y]?
<<
?
"
?
"
;
????????}
????????output?
<<
?endl;
????}
????
return
?output;
}
template
<
class
?T
>
inline?T
*
?TDArray
<
T
>
::
operator
[](
int
?rows)
{
????
return
?p[rows];
}
int
?main(
void
)
{
????TDArray
<
int
>
?iArray?
=
?TDArray
<
int
>
(
2
,?
3
);
????iArray[
1
][
0
]?
=
?
100
;
????cout?
<<
?iArray;
????system(
"
pause
"
);
????
return
?
0
;
}


