歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 具備C++基本功60%以上的函數

具備C++基本功60%以上的函數

日期:2017/3/1 10:13:54   编辑:Linux編程

已知類String的原型為:

  class String
  {
   public:
   String(const char *str = NULL);// 普通構造函數
   String(const String &other); // 拷貝構造函數
   ~String(void); // 析構函數
   String & operator =(const String &other);// 賦值函數
   private:
   char *m_data;// 用於保存字符串
  };

  請編寫String的上述4個函數。

  //普通構造函數
  String::String(const char *str)
  {
   if(str==NULL)
   {
   m_data = new char[1]; // 對空字符串自動申請存放結束標志'\0'的//加分點:對m_data加NULL 判斷
   *m_data = '\0';
   }
   else
   {
   int length = strlen(str);
   m_data = new char[length+1]; // 若能加 NULL 判斷則更好
   strcpy(m_data, str);
   }
  }
  // String的析構函數
  String::~String(void)
  {
   delete ( m_data); // 或delete m_data;
  }
  //拷貝構造函數
  String::String(const String &other) // 輸入參數為const型
  {
   int length = strlen(other.m_data);
   m_data = new char[length+1]; //對m_data加NULL 判斷
   strcpy(m_data, other.m_data);
  }
  //賦值函數
  String & String::operator =(const String &other) // 輸入參數為const
  型
  {
   if(this == &other) //檢查自賦值
   return *this;
   delete (m_data); //釋放原有的內存資源
   int length = strlen( other.m_data );
   m_data = new char[length+1]; //對m_data加NULL 判斷
   strcpy( m_data, other.m_data );
   return *this; //返回本對象的引用
  }

參考《Effective C++》PDF下載見 http://www.linuxidc.com/Linux/2012-08/67301.htm

  剖析:
  能夠准確無誤地編寫出String類的構造函數、拷貝構造函數、賦值函數和析構函數的面試者至少已經具備了C++基本功的60%以上!在這個類中包括了指針類成員變量m_data,當類中包括指針類成員變量時,一定要重載其拷貝構造函數、賦值函數和析構函數,這既是對C++程序員的基本要求,也是《Effective C++》中特別強調的條款。仔細學習這個類,特別注意加注釋的得分點和加分點的意義,這樣就具備了60%以上的C++基本功!

Copyright © Linux教程網 All Rights Reserved