将下列代码中的安全数组改编成安全数组模板类

快乐的小青蛙一只 2012-05-07 10:00:01
要求:将下列代码中的安全数组改编成安全数组模板类
可是不会啊,会的赶紧帮帮忙,跪谢!!!
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 3;
class atype {
int a[SIZE];
public:
atype( ) {
register int i;
for(i=0; i<SIZE; i++) a[i] = i;
}
int &operator[](int i);
};
int &atype::operator[](int i)
{
if(i<0 || i> SIZE-1) {
cout << "\nIndex value of ";
cout << i << " is out-of-bounds.\n";
exit(1);
}
return a[i];
}
int main( )
{
atype ob;
cout << ob[2];
cout << " ";
ob[2] = 25;
cout << ob[2];
ob[3] = 44;
return 0;
}
...全文
119 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
我昨晚最后也弄好了,和你的差不多,呵呵。
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 3;
template <class T>
class atype {
T a[SIZE];
public:
atype( ) {
register int i;
for(i=0; i<SIZE; i++) a[i] = i;
}
T &operator[](int i)
{
if(i<0 || i> SIZE-1) {
cout << "\nIndex value of ";
cout << i << " is out-of-bounds.\n";
exit(1);
}
return a[i];
}
};

int main( )
{
atype<int> ob;
cout << ob[2];
cout << " ";
ob[2] = 25;
cout << ob[2];
ob[3] = 44;
return 0;
}
  • 打赏
  • 举报
回复
这个我知道,谢谢哦。
不过这是我们老师让做的题,他提供的就是上面的代码
yoke_wolf 2012-05-08
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 3;

template <class T>
class atype {
T a[SIZE];
public:
atype( ) {
register int i;
for(i=0; i<SIZE; i++) a[i] = i;
}
T &operator[](int i);
};

template <class T>
T &atype<T>::operator[](int i)
{
if(i<0 || i> SIZE-1) {
cout << "\nIndex value of ";
cout << i << " is out-of-bounds.\n";
exit(1);
}
return a[i];
}
int main( )
{
atype<int> ob;
cout << ob[2];
cout << " ";
ob[2] = 25;
cout << ob[2];
ob[3] = 44;
return 0;
}

确保要使用的数组类型为线性存储结构。
SIZE是windows sdk中的结构体,这样定义可不是好习惯。
另外,你这安全数组,实用性实在。。。。

13,874

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧