函数模板的程序题求助
实现一个三维数组模版CArray3D,可以用来生成元素为任意类型变量的三维数组,使得下面程序输出结果是:0,1,2,3,4,5,6,7,8,9,10,11,12,13,1...
实现一个三维数组模版CArray3D,可以用来生成元素为任意类型变量的三维数组,使得下面程序输出结果是:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,
30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56
,57,58,59,
注意,只能写一个类模版,不能写多个
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;
}
提示:类里面可以定义类,类模版里面也可以定理类模版。例如:
class A
{
class B {
};
};
template <class T>
class S
{
T x;
class K {
Ta;
};
}; 展开
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,
30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56
,57,58,59,
注意,只能写一个类模版,不能写多个
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;
}
提示:类里面可以定义类,类模版里面也可以定理类模版。例如:
class A
{
class B {
};
};
template <class T>
class S
{
T x;
class K {
Ta;
};
}; 展开
展开全部
一层一层的定义下去就可以了
纯体力活 没什么意义 现实中也没什么人会这么用的
#include <iostream>
using namespace std;
template <class T>
class CArray3D
{
public:
template <class T1>
class CArray2D
{
public:
template <class T2>
class CArray1D
{
public:
CArray1D()
{
a = NULL;
}
void set(int n)
{
if(a) delete[]a;
a = new T[n];
}
T2 &operator[](int i)
{
return a[i];
}
~CArray1D(){delete []a;}
private:
T2 * a;
};
CArray2D()
{
a1 = NULL;
}
void set(int m, int n)
{
a1 = new CArray1D<T1> [m];
for(int i = 0; i < m; i ++)
a1[i].set(n);
}
~CArray2D()
{delete [] a1;}
CArray1D<T1> & operator[](int i)
{
return a1[i];
}
private:
CArray1D <T1> * a1;
};
CArray3D(int p, int m, int n)
{
a2 = new CArray2D<T> [p];
for(int i = 0; i < p; i ++)
a2[i].set(m,n);
}
~CArray3D(){delete[] a2;}
CArray2D<T>& operator[](int i)
{
return a2[i];
}
private:
CArray2D<T> *a2;
};
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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询