C++習題與解析(引用-01)

字號:

01.分析以下程序的執(zhí)行結果
    #include
    void main()
    {
    int a;
    int &b=a; // 變量引用
    b=10;
    cout<<"a="<}
    解:
    本題說明變量引用的方法。b是a的引用,它們分配相同的空間,b的值即為a的值。
    所以輸出為 a=10。
    注意:引用是引入了變量或對明的一個 義詞,引用不產生對象的副本。
    02.分析以下程序的執(zhí)行結果
    #include
    class Sample
    {
    int x;
    public:
    Sample(){};
    Sample(int a){x=a;}
    Sample(Sample &a){x=a.x+1;}
    void disp(){cout<<"x="<    };
    void main()
    {
    Sample s1(2),s2(s1);
    s2.disp();
    }
    解:
    本題說明類拷貝構造函數(shù)的使用方法。Sample類的Sample(Sample &a)構造函數(shù)是一個拷貝構造函數(shù),將a對象的x值賦給當前對象的x后加1。
    所以輸出為:x=3。
    03.編寫程序,調用傳遞引用的參數(shù),實現(xiàn)兩個字符串變量的交換。
    例如開始:
    char *ap="hello";
    char *bp="how are you?";
    交換的結果使得ap和bp指向的內容分別為:
    ap: "how are you?"
    bp: "hello"
    解:
    本題使用引用調用(實現(xiàn)由于字符串指針本身就是地址,這里可不使用引用參數(shù),效果是一樣的)。
    程序如下:
    #include
    #include
    void swap(char *&x,char *&y) // 引用作為參數(shù)
    {
    char *temp;
    temp=x;x=y;y=temp;
    }
    void main()
    {
    char *ap="hello";
    char *bp="how are you?";
    cout<<"ap:"    swap(ap,bp);
    cout<<"swap ap,bp"<    cout<<"ap:"    }
    本程序的執(zhí)行結果如下:
    ap:hello
    bp:hoe are you?
    swap ap,bp
    ap:how are you?
    bp:hello