第六周 【项目1-深复制体验】(3)

来源:互联网 发布:github源码如何使用 编辑:程序博客网 时间:2024/05/19 01:11

问题描述:

(1)阅读下面的程序,补足未完成的注释

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include<iostream>    
  2. #include<cstring>    
  3. using namespace std;    
  4. class A    
  5. {    
  6. private:    
  7.     char *a;    
  8. public:    
  9.     A(char *aa)    
  10.     {    
  11.         a = new char[strlen(aa)+1];  //(a)这样处理的意义在于:______________________________    
  12.         strcpy(a, aa);  //(b)数据成员a与形式参数aa的关系:___________________________________    
  13.     }    
  14.     ~A()    
  15.     {    
  16.         delete []a;   //(c)这样处理的意义在于:  ___________________________________________    
  17.     }    
  18.     void output()    
  19.     {    
  20.         cout<<a<<endl;    
  21.     }    
  22. };    
  23. int main(){    
  24.     A a("good morning, code monkeys!");    
  25.     a.output();    
  26.     A b("good afternoon, codes!");    
  27.     b.output();    
  28.     return 0;    
  29. }   

(2)将注释(a)所在的那一行去掉,会出现什么现象?为什么?为什么a数据成员所占用的存储空间要在aa长度基础上加1?若指针a不是指向字符(即不作为字符串的地址),是否有必要加1?
(3)为类A增加复制构造函数,用下面的main函数测试

代码:

#include<iostream>#include<cstring>using namespace std;class A{private:    char *a;public:    A(char *aa)    {        a = new char[strlen(aa)+1];        strcpy(a,aa);    }    A(A &b)    {        a = new char[strlen(b.a)+1];        strcpy(a,b.a);    }    ~A()    {        delete []a;    }    void output()    {        cout<<a<<endl;    }};int main(){    A a("holle world!");    a.output();    A b(a);    b.output();    return 0;}
运行结果:




0 0