第二十三模板 8数组模板 简单

//第二十三模板 8数组模板
/*#include <iostream>
using namespace std;
template<class T, int n>
class people
{
public:
	people();
	people(const T&t);
	T&operator[](int i);
	//注意:
	//这两行定义的带一个参数的构造数和下标运算符数operator[],它们操作的对像不是下面定义的数组成员a[]
	//而是people类的对像
	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; //如果这里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<double, 4>one;
	one.show();

    people<double, 4>*p = new people<double, 4>[4];
	//创建了四个对像,这四个对像按顺序排列在一个数组中,我们把这个数组叫对像数组,这个对像数组的地址返回给了people类的指针p来保存,这本来是一个很简单的在堆中创建的对像数组的过程,但是由于people类是个模板类,因此它的创建形式与普通类有些不同
	for(int i=0; i<9; i++)
	{
	    p[i] =one[i];
		p[i].show();
	}
	return 0;
}*/

  

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