題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
注意:在函數調用里,引用調用與傳址調用的效果相同,但更加簡(jiǎn)潔直觀(guān)。
----------------------------------------------------------
題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++時(shí),也使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類(lèi)的Sample(Sample &a)構造函數是一個(gè)拷貝構造函數,將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();
}
解:
本題說(shuō)明對象引用作為函數參數的作用。Sample類(lèi)中的copy()成員函數進(jìn)行對象拷貝。在main()中先建立對象p和q,p與q對象的x,y值相同,調用func()函數,由于第2個(gè)參數為引用類(lèi)型,故實(shí)參發(fā)生改變;而第1個(gè)參數不是引用類(lèi)型,實(shí)參不發(fā)生改變。所以輸出為:
x=1,y=2
x=30,y=40
-------------------------------------------------------
題5.設計一個(gè)Book類(lèi),包含圖書(shū)的書(shū)名、作者、月銷(xiāo)售量等數據成員,其中書(shū)名和作者采用字符型指針,另有兩個(gè)構造函數、一個(gè)析構函數和兩個(gè)成員函數setbook()和print(),其中setbook()用于設置數據,print()用于輸出數據,其說(shuō)明如下:
void print(ostream& output)
即引用輸出流。
解:
依題意,本題程序如下:
#include<iostream.h>
#include<string.h>
class Book
{
char *title; // 書(shū)名
char *author; // 作者
int numsold; // 月銷(xiāo)售量
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<<" 書(shū)名:"<<title<<endl;
output<<" 作者:"<<author<<endl;
output<<" 月銷(xiāo)售量:"<<numsold<<endl;
}
};
void main()