国家二级C++机试(操作题)模拟试卷647
基本操作题
1.请打开考生文件夹下的解决方案文件proj1,此工程包含一个源程序文件proj1.cpp。文件中将表示数组元素个数的常量size定义为4,并用int类型对类模板进行了实例化。文件中位于每个注释“//ERROR ****found****”之后的一行语句存在错误。请改正这些错误,使程序的输出结果为:
1 2 3 4
注意:模板参数名用T。只修改注释“//ERROR *******found*******”的下一行语句,不要改动程序中的其他内容。
//proj1.cpp
#include<iostream>
using namespace std;
//将数组元素个数size定义为4
//ERRO *******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();
tout<<endl;
return 0;
)
(1)const int Size =4;
(2)void MyClass<T>:Print()
(3)MyClass <int> obj(intArray);
解析:(1)主要考查考生对const变量的掌握,因为const变量不能修改.所以在定义的同时必须初始化。
(2)主要考查考生对模板类的成员函数定义的掌握,因为MyClass类是模板类,所以在定义该函数时要加上模板标识符\\
简单应用题
2.请打开考生文件夹下的解决方案文件proj2,该工程中包含一个程序文件main.cpp,其中有“书”类Book及其派生出的“教材”类TeachingMaterial的定义,还有主函数rnain的定义。请在程序中“//*******found*******”下的横线处填写适当的代码,然后删除横线,以实现上述类定义和函数定义。此程序的正确输出结果应为:
教材名:c++语言程序设计
页 数:299
作 者:张三
相关课程:面向对象的程序设计
注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“//*******found*******”。
#include<iostream>
using namespace std;
class Book( //“书”类
char * title; //书名
int num pages;//页数
char * writer;//作者姓名
public:
Book(const char * the_title,
int pages,const char*thewriter):num_Pages(pages){
title=new char[strlen(the title)+1];
strcpy(title,the_title);
//*******found*******
________________
strcpy(writer,the_writer);
)
//*******found*******
一Book(){________}
int numOfPages()const{returnnum_pages;)//返回书的页数
const char{theTitle()const{return title;}//返回书名
const char * theWriter () const{return writer;}//返回作者名
};
class TeachingMaterial:public
Book{
//“教材”类
char * course;
public:
TeachingMaterial(const char*the title,int pages,constchar*the_writer,const char * the course)
//*******found*******
:________{
course=new char[strlen(the course)+1 ];
strcpy(course,the_course);
}
~TeachingMaterial(){delete[ ]course;}
const char * theCourse()
const{return course;) //返回相关课程的名称
};
int main(){
TeachingMaterial a_book(”C++语言程序设计”,299,”张三”,”面向对象的程序设计”);
cout<<-’教材名:”<<a book.theTitle()<<endl
<<”页 数:-·<<a book.numOfPages()<<endl
<<\\
(1)writer = new char[strlen(the_writer)+1];
(2)delete [ ]title,writer;
(3)Book(the_title,pages,the_writer)
(4)a_book.theCourse()<< endl
解析:(1)主要考查考生对动态分配的掌握,在填空前可以参考title的初始化,即先分配空间,再使用strcpy函数拷贝字符串,因此这里使用writer = new char[strlen(the_writer)+1];语句给miter分配空间,注意分配空间的大小应为字符串长度加1。
(2)主要考查考生对析构函数的掌握,要填写的内容是析构函数的函数体,因为有两个动态数组title和writer,所以要释放两个动态数组空间,使用语句~Book(){delete[ ]title,writer;}来完成。
(3)主要考查考生对派生类的构造函数的掌握,派
本文档预览:3600字符,共6412字符,源文件无水印,下载后包含无答案版和有答案版,查看完整word版点下载