1.改错题1. 使用VC6打开考生文件夹下的工程test15_1,此工程包含一个源程序文件test15_1.cpp,但该程序运行有问题,请改正程序中的错误,使该程序的输出结果如下:
My object has member 7
源程序文件test15_1.cpp清单如下:
#include<iostream.h>
class MyClass
{
public:
MyClass(int mem){member=mem;}
~MyClass(){}
int GetAge()const{ return member;}
private:
int member;
};
/*****+********+** found *************/
void main()
{
int mem=7;
/*************** found ***************/
MyClass myObj=MakeObject(mem);
cout<<"My object has member"<<myObj->GetAge()<<endl;
/***************** found ****************/
delete;
}
MyClass *MakeObject(int mem)
{
MyClass *pMyClass=new MyClass(mem);
return pMyClass;
}
(1)添加函数定义MyClass *MakeObject(int mem);
(2)错误:MyClass myObj=MakeObject(mem);
正确:MyClass *myObj=MakeObject(mem);
(3)错误:delete;
正确:delete myObj;
[解析]
(1)主要考查考生对于函数定义规则的理解,在使用前先定义,这是规定;
(2)主要考查考生对于指针的掌握,因为函数返回值为指针,所以返回值必须赋值给一个指针类型的变量;
(3)主要考查考生是否会使用delete释放空间,使用delete删除一个指针时,只需要直接把指针变量的名称写在后面。
2.简单应用题1. 请编写一个函数char MaxCharacmr(char *str),该函数返回参数str所指向的字符串中具有最大ASCII码的那个字符(如字符串“world”中字符‘w’具有最大的ASCII码)。当str所指向的字符串为空时,则返回空字符0x0或‘\0’。
输出结果如下:
Good Morning!
Max char:r
注意:部分源程序已存在文件test15_2.cpp中。
请勿修改主函数main和其他函数中的任何内容,仅在函数MaxCharacter的花括号中填写若干语句。
文件test15_2.cpp的内容如下:
#include<iostream.h>
#include<string.h>
char MaxCharacter(char *str);
void main()
{
char str[100];
strcpy(str,"Good Morning!");
char maxc=MaxCharacter(str);
cout<<str<<endl;
cout<<"Max char:"<<maxc<<endl;
}
char MaxCharacter(char*str)
{
}
char MaxCharacter (char *str)
{
if(str==NULL)
return 0x0;
char maxChar=0x0;
int len=strlen(str);
for(int i=0;i<len;i++)
{
if(str[i]>maxChar)
maxChar=str[i];
}
return maxChar;
}
[解析] 本题考查的是考生应用for和if等基本控制语句解决实际问题的能力。注意字符的大小可以直接比较,实际上比较的就是字符的ASCII码的值。
3.综合应用题1. 使用VC6打开考生文件夹下的工程test15_3。此工程包含一个test15_3.cpp,其中定义了类Time和Timex,Timex公有继承Time,但定义并不完整。请按要求完成下列操作,将程序补充完整。
(1)完成类Time构造函数的定义,将数据成员hours和minutes分别初始化为参数new_hours和new_minutes的值。请在注释“//**1**”之后添加适当的语句。
(2)完成类Timex的构造函数的定义,注意参数的传递。请在注释“//**2**”之后添加适当的语句。
(3)请按时间格式“hour:minute”和“hour:minute:second”分别输出对象time1和time2所表示的时间,注意必须使用已经定义的成员函数。请在注释“//**3**”之后添加适当的语句。
输出结果如下:
20:30
10:45:34
注意:除在指定的位置添加语句外,请不要改动程序中的其他语句。
源程序文件test15_3.cpp清单如下:
#include<iostream.h>
class Time
{
public:
Time(int new_hours,int new_minutes)
{
// ** 1 **
}
int get_hours();
int get_minutes();
protected:
int hours,minutes;
};
int Time::get_hours()
{
return hours;
}
int Time::get_minutes()
{
return minutes;
}
class Timex:public Time
{
public:
Timex(int new_hours,int new_minutes,int new_seconds);
int get_seconds();
protected:
int seconds;
};
// ** 2 **
{
seconds=new_seconds;
}
int Timex::get_seconds()
{
return seconds;
}
void main()
{
Time time1(20,30);
Timex time2(10,45,34);
// ** 3 **
}
(1)
hours=new_hours;
minutes=new_minutes;
(2)
Timex::Timex(int new_hours,int new_minutes,
int new_seconds):Time(new_hours,new_minutes)
(3)
cout<<time1.get_hours()<<":"<<time1.get_minutes()<<end1;
cout<<time2.get_hours()<<":"<<time2.get_minutes()<<":"<<time2.get_seconds()<endl;
[解析] 本题主要考查考生对于类和派生类构造函数的定义以及成员函数的使用,注意(2)中派生类构造函数中必须包括向基类传递参数的调用,应该使用参数列表完成这一操作。