第二十三模板 9对像数组模板 简单

//第二十三模板 9对像数组模板
//我们也可以直接使用对像模板来构造对像数组
//people<people<int,5>,10>two;
//该语句创建了一个包含10个元素对像数组two,每个对像又拥有一个包含5个int元素的数组,因此它可以看作如下二维数组
//int two[10][5]
//注意,在模板的表示语法中,维的顺序与正常的二维数组的顺序相反
//people<people<int,5>,10>one; 可看做是 one[10][5];
/*#include <iostream>
using namespace std;
template<class T, int n>
class people
{
public:
	people();
	people(const T&t);
	T& operator[](int i);
	void show();
private:
	T a[n];
};

template<class T, int n>
people<T,n>::people()
{
     cout<<"执行构造函数"<<endl;
	 for(int i=0; i<n; i++){
	      a[i] = (i+1);
	 }
}

template<class T, int n>
people<T,n>::people(const T&t)
{
    cout<<"执行带一个参数的构造函数"<<endl;
	for(int i=0; i<n; i++){
	     a[i] = t;
	}
}

template<class T, int n>
T&people<T, n>::operator[](int i)
{
    cout<<"执行下标运算符函数operator[]"<<endl;
	if(i<0 || i>=n){
	   cout<<"超出了数组的下标:第"<<i<<endl;
	   exit(EXIT_FAILURE);
	}
	return a[i];
}

template<class T, int n>
void people<T, n>::show()
{
	for(int i=0; i<n; i++){
	    cout<<"a["<<i<<"]:"<<a[i]<<"\t";
	}
	cout<<endl;
}
int main()
{
	people<people<int,2>,3>two;
	int obj = 1;
	for(int i=0; i<4; i++)
	{
	    int sum=1;
		for(int j=0; j<2; j++){
		   cout<<"\ntwo["<<i<<"]["<<j<<"]:"<<two[i][j]<<"\n";
		   cout<<"第"<<sum++<<"个无素输出完毕\n";   
		}
		cout<<"第"<<obj++<<"个对像中的数组无素输出完毕"<<endl;
	}

    return 0;
}*/

  

原文地址:https://www.cnblogs.com/xiangxiaodong/p/2711684.html