模板及运算符重载的一个小例子 供学习
#include "stdafx.h"
#include <assert.h>
#include <iostream>
using namespace std;
template<class T> class array//模板数组类
{
enum {size = 100};
T A[size];
public:
T& operator[] (int index);//运算符 这里设为引用返回类型 由于可读可写 所以不设置为const 类型
};
template<class T> T& array<T>::operator[] (int index)
{
assert(index >= 0 && index <size);
return A[index];
}
void main()
{
array<int> ia;
array<float>fa;
for (int i = 0; i < 20; i++)
{
ia[i] = i*i;
fa[i] = float(i) * 1.414;
}
for (int j= 0; j < 20; j++)
{
cout<<j<<": "<<ia[j]<<", "<<fa[j]<<endl;
}
getchar();
};