第九周 【项目-深复制体验】2

  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;  

  1. }  


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


运行崩溃,因为a没有空间储存。   因为还有\0。        没有

你可能感兴趣的:(第九周 【项目-深复制体验】2)