使用VC6打开考生文件夹下的工程test37_1,此工程包含一个源程序文件test37_1.cpp,但该程序运行有问题,请改正函数中的错误,使该程序的输出结果为:
0 1 4 9 16 25 36 49 64 81
源程序文件test37_1.cpp清单如下:
#include<iostream.h>
template <class T, int N = 100> class Vector
T vec[N];
public:
void set(int pos, T val);
T get(iht pos);
/***************** found *****************/
template <class T, int N> void Vector<T, N>::set(int pos, T val)
vec[pos] = val;
/***************** found *****************/
template <class T, int N> Vector<T, N>::get(int pos)
return vec[pos];
int main ()
Vector<double, 10> v;
int i = 0;
double d = 0.0;
for (i = 0; i < 10; i++)
v.set(i, double(i * i));
for (i = 0; i < 10; i++)
cout<<v.get(i)<<" ";
cout<<end1;
/***************** found *****************/
参考答案:(1) 错误:}
正确:};
(2) 错误:template<class T,int N>Vector<T,N>::get(int pos)
正确:template<class T,int N>T Vector<T,N>::get(int pos)
(3) 错误:缺少返回值
正确:加入 return 0;
解析:
(1)主要考查考生对于类定义的理解,即使使用了类模板,在类定义的结尾仍然需要使用分号,这是C++的规定;
(2)主要考查考生是否会掌握了模板类的定义,template是关键字,在<>中间是类型的定义,题目中Vector是一个类的名称,前面应该有该模板的名称,即T,这样才是完整的定义;
(3)主要考查考生对于函数返回值的掌握,任何返回值类型不为int型的函数最后都必须使用returen语句返回对应类型的值,就算是main函数也不例外。