您的位置:首页 > 其它

模板及运算符一个例子

2011-01-27 09:44 239 查看
模板及运算符重载的一个小例子 供学习

#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();

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: