请打开考生文件夹下的解决方案文件proj1,此工程包含一个源程序文件proj1.cpp。文件中将表示数组元素个数的常量Size定义为4,并用int类型对类模板进行了实例化。文件中位于每个注释“//ERROR***found****”之后的一行语句存在错误。请改正这些错误,使程序的输出结果为:
1 2 3 4
注意:模板参数名用T。只修改注释“//ERROR ********found********”的下一行语句,不要改动程序中的其他内容。
//proj1.cpp
#include<iostream>
using namespace std;
//将数组元素个数Size定义为4
//ERROR ********found********
conSt int size;
template<typename T>
Class MyClass
{
public:
Myclass(T*P)
{
for(int i=0 ; i<size;i++)
array[i]=p[i];
}
void Print();
private:
T array[size];
};
template<typename T>
//ERROR ********found********
void Myclass::Print()
{
for(int i=0;i<size;i++)
cout<<array[i]<<'\t';
}
int main()
{
int intArray[Size]={1,2,3,4};
//ERROR ********found********
MyClass<double>obj {intArray);
obj.Print();
Cout<<endl;
return 0;
}
【正确答案】(1)const int Size=4;
(2)void MyClass<T>::Print()
(3)MvClass<int>obj(intArray);
【答案解析】(1)主要考察考生对const变量的掌握,因为const变量不能修改,所以在定义的同时必须初始化。
(2)主要考查考生对模板类的成员函数定义的掌握,因为MyClass类是模板类,所以在定义该函数时要加上模板标识符“<T>”,即语句void MvClass<T>::Print()
(3)主要考查考生对模板类构造函数的调用的理解,从上一条语句int intArray[Size]={1,2,3,4};中可以知道intArray为int型,因此定义obj时要使用<int>,即MyClass<int>obj(intArray):。