1. 程式人生 > >編寫類String 的建構函式、拷貝建構函式、解構函式和賦值函式

編寫類String 的建構函式、拷貝建構函式、解構函式和賦值函式

 編寫類String 的建構函式、解構函式和賦值函式,已知類String 的原型為:
class String
{
public:
String(const char *str = NULL); // 普通建構函式
String(const String &other); // 拷貝建構函式
~ String(void); // 解構函式
String & operate =(const String &other); // 賦值函式
private:
char *m_data; // 用於儲存字串
}; 

  1. #include <iostream>
  2. class String  
  3. {  
  4. public:  
  5.     String(constchar *str=NULL);//普通建構函式
  6.     String(const String &str);//拷貝建構函式
  7.     String & operator =(const String &str);//賦值函式
  8.     ~String();//解構函式
  9. protected:  
  10. private:  
  11.     char* m_data;//用於儲存字串
  12. };  
  13. //普通建構函式
  14. String::String(constchar *str)
  15. {  
  16.     if (str==NULL)
  17.     {  
  18.         m_data=new
    char[1]; //對空字串自動申請存放結束標誌'\0'的空間
  19.         if (m_data==NULL)
  20.         {//記憶體是否申請成功
  21.           std::cout<<"申請記憶體失敗!"<<std::endl;  
  22.           exit(1);  
  23.         }  
  24.         m_data[0]='\0';  
  25.     }  
  26.     else
  27.     {  
  28.         int length=strlen(str);  
  29.         m_data=newchar[length+1];  
  30.         if (m_data==NULL)
  31.         {//記憶體是否申請成功
  32.             std::cout<<"申請記憶體失敗!"<<std::endl;  
  33.             exit(1);  
  34.         }  
  35.         strcpy(m_data,str);  
  36.     }  
  37. }  
  38. //拷貝建構函式
  39. String::String(const String &other)
  40. //輸入引數為const型
  41.     int length=strlen(other.m_data);  
  42.     m_data=newchar[length+1];  
  43.     if (m_data==NULL)
  44.     {//記憶體是否申請成功
  45.         std::cout<<"申請記憶體失敗!"<<std::endl;  
  46.         exit(1);  
  47.     }  
  48.     strcpy(m_data,other.m_data);  
  49. }  
  50. //賦值函式
  51. String& String::operator =(const String &other)
  52. {//輸入引數為const型
  53.     if (this == &other//檢查自賦值
  54.     {  return *this; }
  55.     delete [] m_data;//釋放原來的記憶體資源
  56.     int length=strlen(other.m_data);  
  57.     m_data= newchar[length+1];  
  58.     if (m_data==NULL)
  59.     {//記憶體是否申請成功
  60.         std::cout<<"申請記憶體失敗!"<<std::endl;  
  61.         exit(1);  
  62.     }  
  63.     strcpy(m_data,other.m_data);  
  64.     return *this;//返回本物件的引用
  65. }  
  66. //解構函式
  67. String::~String()
  68. {  
  69.     delete [] m_data;  
  70. }  
  71. void main()
  72. {  
  73.     String a;  
  74.     String b("abc");  
  75.     system("pause");  
  76. }