#include
for (int i=0;i
t=a[i], a[i]=a[n-1-i], a[n-1-i]=t; }
void main ()
{int a[5]={10,21,34,4,50};
double d[6]={11.1,10.1,9.1,8.1,7.1}; f(a,5);f(d,6);
for (i=0;i<6;i++) cout << d[i] << \cout << endl; }
答案:T a[],int n,T t=0;
[解析]不同的数据类型的调用,使用了模板。f函数增加t变量,因为实参类型不同,所以t的 类型应该是T类型的。
2. 在下面程序的底画线处填上适当的字句,使该程序执行结果为40。 #include
Test (int i=0) {x=i+x;} int Getnum()
{return Test::x+7;} };
_______; void main() {Test test;
cout<
答案:static int x;,int Test::x=30;
[解析]从成员函数访问方式类名::成员可知是静态成员所以static int x;从结果要对初始 化为30,且在类外进行初始化, int Test::x=30;。
3. 在下列程序的空格处填上适当的字句,使输出为:0,2,10。 #include
Magic(double d=0.00):x(fabs(d))
9
{}
Magic operator+(______) {
return Magic(sqrt(x*x+c.x*c.x)); }
_______operator<<(ostream & stream,Magic & c) { stream<
void main() {Magic ma;
cout<
答案:operator+(Magic&c),friend ostream&operator
[解析]对加法进行重载,operator+(Magic & c),是对插入符进行重载,要访问成员所以定义 为友元函数,friend ostream & operator。
4. 下面是一个输入半径,输出其面积和周长的C++程序,在下划线处填上正确的语句。 #include
double l=2.0*pi*rad; double s=pi*rad*rad;
cout<<\\n The long is:\cout<<\:\
答案:using namespace std,#define pi 3.14159
[解析]进行输入或输出要引入iostream, 所以using namespace std;从标点看没有分号,所以 使用宏定义,#define pi 3.14159。 5. 程序实现大写字母转换成小写字母。 #include
答案:int i=32;,a>=A && a<=Z
[解析]大写字母变小写字母相差32,需要对i声明并初始化。大写字母变小写字母。要判断字 符是大写字母。
10
五、程序分析题(本大题共4小题,每小题5分,共20分) 1. 给出下面程序输出结果。
#include
virtual void print()
{cout<< \};
class b:public a {};
class c:public b {public:
void print(){cout<<\};
void show(a *p) {(*p).print(); }
void main() {a a; b b; c c;
show(&a); show(&b); show(&c); }
答案:a prog... a prog... c prog...
[解析]考查多态性的。a类对象调用本身的虚函数,b类因为没有覆写print,所以仍然调用基 类的虚函数。而c类重新定义print虚函数,所以调用c类的print。 2. 给出下面程序输出结果。 #include
{long a=10,b=30,l=0; if(a%2==0) a++;
for(long m=a;m<=b;m+=2) if(fun(m)) {if(l++==0) cout <
cout <
bool fun(long n)
11
{int sqrtm=(int)sqrt(n); for(int i=2;i<=sqrtm;i++) if(n%i==0) return false; return true; }
答案:11 13 17 19 23 29
[解析]循环体用来判断n是否是质数的函数,在main函数判断10~30之间质数。 3. 给出下面程序输出结果。 #include
Test(int i,int j=0) {x=i;y=j;}
int get(int i,int j) {return i+j;} };
void main()
{Test t1(2),t2(4,6);
int (Test::*p)(int,int=10); p=Test::get;
cout<<(t1.*p)(5)<
cout<<(p1->*p)(7,20)<
答案:15 27
[解析]指向类成员函数的指针的使用,*p指向Test类中有两个参数的函数的一个指针。 P=Test::get.这样p就和get发生了联系。(t1.*p)(5)等价于调用一个参数的get函数。 4. #include
char level[7];
friend class process; // 说明友元类 public:
student(char na[],int d) { strcpy(name,na); deg=d; } };
class process { public:
void trans(student &s)
12