第九週上機實踐項目 項目1-深複製體驗

問題及代碼:

(1)閱讀下面的程序,補足未完成的註釋

#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
    char *a;
public:
    A(char *aa) 
    {
        a = new char[strlen(aa)+1];  //(a)這樣處理的意義在於:______________________________
        strcpy(a, aa);  //(b)數據成員a與形式參數aa的關係:___________________________________
    }
    ~A() 
    {
        delete []a;   //(c)這樣處理的意義在於:  ___________________________________________
    }
    void output() { cout<<a<<endl; }
};
int main(){
    A a("good morning, code monkeys!");
    a.output();
    A b("good afternoon, codes!");
    b.output();
    return 0;
}

(2)將註釋(a)所在的那一行去掉,會出現什麼現象?爲什麼?爲什麼a數據成員所佔用的存儲空間要在aa長度基礎上加1?若指針a不是指向字符(即不作爲字符串的地址),是否有必要加1?
(3)爲類A增加複製構造函數,用下面的main函數測試

 

int main()
{
    A a("good morning, code monkeys!");
    a.output();
    A b(a);
    b.output();
    return 0;
}
/* 
 Copyright(c)2016,煙臺大學計算機與控制工程學院 
  All rights reserced 
 文件名稱:test.cpp 
 作    者:蔡汝佳 
 完成日期:2016年5月9日 
 版 本 號:v1.0 
 問題描述:
 輸入描述: 
 程序輸出: 
*/  

#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
    char *a;
public:
    A(char *aa)
    {
        a = new char[strlen(aa)+1];  //(a)這樣處理的意義在於:______________________________
        strcpy(a, aa);  //(b)數據成員a與形式參數aa的關係:___________________________________
    }

    A(A &b)
    {
        a=new char[strlen(b.a)+1];
        strcpy(a,b.a);
    }
    ~A()
    {
        delete []a;   //(c)這樣處理的意義在於:  ___________________________________________
    }
    void output() { cout<<a<<endl; }
};
int main()
{
    A a("good morning, code monkeys!");
    a.output();
    A b(a);
    b.output();
    return 0;
}

 

 

運行結果:

知識點總結:

 

學習心得:



發佈了86 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章