数据结构老师给的源码有bug,哪位大神帮我看看

#include <iostream.h>
template <typename T>

class Array{
T data[MaxSize];
unsigned len;
public :
Array(unsigned size, T init_data){
len=size;
for (unsigned k=0;k<len;k++)
data[k]=init_data;
}
T& get_data(unsigned index){
if (index>=0 && index<len)
return data[index];
else
exit(0);
}
};
void main(){
Array<int> arr_i(5,1);
Array<float> arr_f(5,10.23);
Array<char> arr_c(5,'M');
for (int k=0;k<5;k++)
cout<<arr_i.get_data(k)<<" ";
cout<<endl;
for (k=0;k<5;k++)
cout<<arr_f.get_data(k)<<" ";
cout<<endl;
for (k=0;k<5;k++)
cout<<arr_c.get_data(k)<<" ";
cout<<endl;
}

有几个错误:1、头文件名称不对。2、常量没有定义。3、变量类型没有定义。
修改后如下:
//#include <iostream.h>这头文件修改成 #include <iostream>
#include <iostream>
using namespace std;//多加这一行
#define MaxSize 50//需要定义这个常量(值可根据实际来修改)
template <typename T>
class Array{
T data[MaxSize];
unsigned len;
public :
Array(unsigned size, T init_data){
len=size;
for (unsigned k=0;k<len;k++)
data[k]=init_data;
}
T& get_data(unsigned index){
if (index>=0 && index<len)
return data[index];
else
exit(0);
}
};
void main(){
Array<int> arr_i(5,1);
Array<float> arr_f(5,10.23);
Array<char> arr_c(5,'M');
for (int k=0;k<5;k++)
cout<<arr_i.get_data(k)<<" ";
cout<<endl;
for (int k=0;k<5;k++)//在k的前面加上int类型
cout<<arr_f.get_data(k)<<" ";
cout<<endl;
for (int k=0;k<5;k++)//在k的前面加上int类型
cout<<arr_c.get_data(k)<<" ";
cout<<endl;
}追问

有新bug

你前面说的我刚看懂,谢谢

在帮我看下新问题吧

追答

回复你的代码,我是调试过的,有什么新问题请明示。我这里运行结果如下:
1 1 1 1 1
10.23 10.23 10.23 10.23 10.23
M M M M M

追问

我知道了

用了exit(0)

没有这个头文件#include

温馨提示:内容为网友见解,仅供参考
第1个回答  2016-09-22
#include <stdlib.h>
#include <iostream.h>

#define MaxSize (5)

template <typename T> 

class Array{  
T data[MaxSize];
unsigned  len;
public :
Array(unsigned size, T init_data){
len=size;
for (unsigned k=0;k<len;k++)
data[k]=init_data;
}
T& get_data(unsigned index){
if (index>=0 && index<len)
return data[index];
else
exit(0);
}
};
void main(){
Array<int>  arr_i(5,1);
Array<float>  arr_f(5,10.23);
Array<char>  arr_c(5,'M');
for (int k=0;k<5;k++)
cout<<arr_i.get_data(k)<<" ";
cout<<endl;
for (k=0;k<5;k++)
cout<<arr_f.get_data(k)<<" ";
cout<<endl;
for (k=0;k<5;k++)
cout<<arr_c.get_data(k)<<" ";
cout<<endl;
}

追问

能解释下为什么用#include

#define MaxSize (5)

这两个不太懂

追答

exit包含在stdlib.h里

MaxSize 没定义,定义数组应该是数字,不应选变量,就用define定义了

追问

谢谢🙏

本回答被网友采纳