string深刻認識

        string的本質其實是個類,而char十個內建類型 不屬於類。其次在初始化的時候,一點要注意string不可以設置爲null,(如果你以前習慣 char * str = null),這是因爲string的賦值函數的實現會直接傳入進入 調用這個null的內部變量出錯。大家可以看如下代碼

  1.  String & String::operate =(const String &other)  
  2.  {     
  3.   
  4.          // (1) 檢查自賦值  
  5.   
  6.          if(this == &other)  
  7.   
  8.              return *this;  
  9.   
  10.           
  11.   
  12.          // (2) 釋放原有的內存資源  
  13.   
  14.          delete [] m_data;  
  15.   
  16.           
  17.   
  18.          // (3)分配新的內存資源,並複製內容  
  19.   
  20.      <span style="white-space:pre"> </span>int length = strlen(other.m_data);  
  21.   
  22.      <span style="white-space:pre"> </span>m_data = new char[length+1];  
  23.   
  24.         strcpy(m_data, other.m_data);  
  25.   
  26.           
  27.          // (4)返回本對象的引用  
  28.          return *this;  
  29. }
int length = strlen(other.m_data); 執行這句話爲錯,所以初始化可以什麼都不寫,如string str。就執行如下代碼

   

  1. String::String(const char *str)  
  2. {  
  3.        if(str==NULL)  
  4.        {  
  5.            <span style="white-space:pre">   </span>m_data = new char[1]; // 得分點:對空字符串自動申請存放結束標誌'\0'的空  
  6.                                      //加分點:對m_data加NULL 判斷  
  7.            <span style="white-space:pre">   </span>*m_data = '\0';  
  8.        }      
  9.        else  
  10.        {  
  11.         <span style="white-space:pre">  </span>int length = strlen(str);  
  12.         <span style="white-space:pre">  </span>m_data = new char[length+1]; // 若能加 NULL 判斷則更好  
  13.         <span style="white-space:pre">  </span>strcpy(m_data, str);  
  14.        }  
  15. }  
  16.   

       默認的情況下string定義const char * str = NULL

       所以會執行if, 這裏面會涉及內存開闢已經完成,沒有內存可以分配情況

      

  1.  {  
  2.            <span style="white-space:pre">   </span>m_data = new char[1]; // 得分點:對空字符串自動申請存放結束標誌'\0'的空  
  3.                                      //加分點:對m_data加NULL 判斷  
  4.            <span style="white-space:pre">   </span>*m_data = '\0';  
  5.        }      

              這裏面可以寫成

  1.  {  
  2.            <span style="white-space:pre">   </span>m_data = new char[1]; // 得分點:對空字符串自動申請存放結束標誌'\0'的空  
  3.                                      //加分點:對m_data加NULL 判斷  
  4.      if(m_data != NULL)
  5.      {
  6.            <span style="white-space:pre">   </span>*m_data = '\0';
  7.      }  
  8.  }      
               


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章