实现一个三维数组模版CArray3D,可以用来生成元素为任意类型变量的三维数组
1.用一个模板实现:
#include <iostream>
using namespace std;
template <class T>
class CArray3D{
template <class T>
class CArray2D{
template <class T>
class CArray1D {
public:
CArray1D() :p(NULL){}
void set(T a)
{
p = new T[a];
_a = a;
}
inline T& operator[](long elem) const
{
// assert( elem >= 0 && elem < _a );
return p[elem];
}
~CArray1D()
{
delete[] p;
};
private:
T* p;
T _a;
};
public:
CArray2D() :p(NULL){}
void set(T a, T b){
p = new CArray1D<T>[a];
for (int i = 0; i<a; i++){
p[i].set(b);
}
_b = b;
}
inline CArray1D<T>& operator[](long elem) const
{
// assert( elem >= 0 && elem < _b );
return p[elem];
}
~CArray2D()
{
delete[] p;
}
private:
CArray1D<T>* p;
T _b;
};
public:
CArray3D(T a, T b, T c){
p = new CArray2D<T>[a];
for (int i = 0; i<a; i++){
p[i].set(b, c);
}
_c = c;
}
inline CArray2D<T>& operator[](long elem) const
{
// assert( elem >= 0 && elem < _c );
return p[elem];
}
~CArray3D()
{
delete[] p;
}
private:
CArray2D<T>* p;
T _c;
};
int main()
{
CArray3D<int> a(3, 4, 5);
int No = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
for (int k = 0; k < 5; ++k)
a[i][j][k] = No++;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
for (int k = 0; k < 5; ++k)
cout << a[i][j][k] << ",";
return 0;
}
2.多个模板实现:
#include <iostream>
using namespace std;
template <class T>
class CArray1D {
public:
CArray1D() :p(NULL){}
void set(T a)
{
p = new T[a];
_a = a;
}
inline T& operator[](long elem) const
{
// assert( elem >= 0 && elem < _a );
return p[elem];
}
~CArray1D()
{
delete[] p;
}
private:
T* p;
T _a;
};
template <class T>
class CArray2D{
public:
CArray2D() :p(NULL){}
void set(T a, T b){
p = new CArray1D<T>[a];
for (int i = 0; i<a; i++){
p[i].set(b);
}
_b = b;
}
inline CArray1D<T>& operator[](long elem) const
{
// assert( elem >= 0 && elem < _b );
return p[elem];
}
~CArray2D()
{
delete[] p;
}
private:
CArray1D<T>* p;
T _b;
};
template <class T>
class CArray3D{
public:
CArray3D(T a, T b, T c){
p = new CArray2D<T>[a];
for (int i = 0; i<a; i++){
p[i].set(b, c);
}
_c = c;
}
inline CArray2D<T>& operator[](long elem) const
{
// assert( elem >= 0 && elem < _c );
return p[elem];
}
~CArray3D()
{
delete[] p;
}
private:
CArray2D<T>* p;
T _c;
};
int main()
{
CArray3D<int> a(3, 4, 5);
int No = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
for (int k = 0; k < 5; ++k)
a[i][j][k] = No++;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 4; ++j)
for (int k = 0; k < 5; ++k)
cout << a[i][j][k] << ",";
return 0;
}