题1.分析以下程序的执行结果 #include<iostream.h> void swap(int &x,int &y) { int temp; temp=x; x=y; y=temp; } void main() { int x=10,y=20; swap(x,y); cout<<"x="<<x<<",y="<<y<<endl; } 解: 这里的函数采用引用调用的方式,所以输出为:x=20,y=10 注意:在函数调用里,引用调用与传址调用的效果相同,但更加简洁直观。 ---------------------------------------------------------- 题2.分析以下程序的执行结果 #include<iostream.h> void main() { int a[]={10,20,30,40},*pa=a; int *&pb=pa; pb++; cout<<*pa<<endl; } 解: pa为数组的指针,首先指向a[0],pb是pa的引用,当执行pb++时,也使pa指向了a[1],所以输出为:20 ------------------------------------------------------------- 题3.分析以下程序的执行结果 #include<iostream.h> class Sample { int x; public: Sample(){}; Sample(int a){x=a;} Sample(Sample &a){x=a.x++ +10;} void disp(){cout<<"x="<<x<<endl;} }; void main() { Sample s1(2),s2(s1); s1.disp(); s2.disp(); } 解: Sample类的Sample(Sample &a)构造函数是一个拷贝构造函数,将a对象的x增1然后加上10后赋给当前对象的x,由于a是引用对象,所以输出为: x=3 // ++运算的结果 x=12 // 2+10 -------------------------------------------------------------- 题4.分析以下程序的执行结果 #include<iostream.h> class Sample { int x,y; public: Sample(){x=y=0;} Sample(int i,int j){x=i;y=j;} void copy(Sample &s); void setxy(int i,int j){x=i;y=j;} void print(){cout<<"x="<<x<<",y="<<y<<endl;} }; void Sample::copy(Sample &s) { x=s.x;y=s.y; } void func(Sample s1,Sample &s2) { s1.setxy(10,20); s2.setxy(30,40); } void main() { Sample p(1,2),q; q.copy(p); func(p,q); p.print(); q.print(); } 解: 本题说明对象引用作为函数参数的作用。Sample类中的copy()成员函数进行对象拷贝。在main()中先建立对象p和q,p与q对象的x,y值相同,调用func()函数,由于第2个参数为引用类型,故实参发生改变;而第1个参数不是引用类型,实参不发生改变。所以输出为: x=1,y=2 x=30,y=40 ------------------------------------------------------- 题5.设计一个Book类,包含图书的书名、作者、月销售量等数据成员,其中书名和作者采用字符型指针,另有两个构造函数、一个析构函数和两个成员函数setbook()和print(),其中setbook()用于设置数据,print()用于输出数据,其说明如下: void print(ostream& output) 即引用输出流。 解: 依题意,本题程序如下: #include<iostream.h> #include<string.h> class Book { char *title; // 书名 char *author; // 作者 int numsold; // 月销售量 public: Book(){} Book(const char *str1,const char *str2,const int num) { int len=strlen(str1); title=new char[len+1]; strcpy(title,str1); len=strlen(str2); author=new char[len+1]; strcpy(author,str2); numsold=num; } void setbook(const char *str1,const char *str2,const int num) { int len=strlen(str1); title=new char[len+1]; strcpy(title,str1); len=strlen(str2); author=new char[len+1]; strcpy(author,str2); numsold=num; } ~Book() { delete title; delete author; } void print(ostream& output) // 输出流引用作为参数 { output<<"输出数据"<<endl; output<<" 书名:"<<title<<endl; output<<" 作者:"<<author<<endl; output<<" 月销售量:"<<numsold<<endl; } }; void main() { Book obj1("C语言程序设计","谭浩强",800),obj2; obj1.print(cout); obj2.setbook("C++语言程序设计","李春葆",300); obj2.print(cout); } 本程序的执行结果如下: 输出数据 书名:C语言程序设计 作者:谭浩强 月销售量:800 输出数据 书名:C++语言程序设计 作者:李春葆 月销售量:300 |