溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

c++編寫String類代碼實(shí)例

發(fā)布時(shí)間:2020-09-26 15:26:23 來源:腳本之家 閱讀:237 作者:ypshowm 欄目:編程語言

本文實(shí)例為大家分享了c++編寫String類的具體代碼,供大家參考,具體內(nèi)容如下

class String
{
public:
  String(const char* = nullptr); //普通構(gòu)造函數(shù)
  String(const String& other);  //拷貝構(gòu)造函數(shù)
  ~String(void); //析構(gòu)函數(shù)
  String& operator = (const String& other);  //賦值函數(shù)
  
private:
  char* m_data;
};
 
//普通構(gòu)造函數(shù)
String::String(const char* str)
{
  if(str == nullptr){
    m_data = new char[1];  //對空字符自動(dòng)申請存放結(jié)束標(biāo)志'\0'的空
    *m_data = '\0';
  }else{
    m_data = new char[strlen(str) + 1];  //+1是為了多余一個(gè)字符存放'\0'
    strcpy(m_data, str);
  }
}
 
//拷貝構(gòu)造函數(shù)
String::String(const String& other)
{
  if(other == nullptr){
    m_data = nullptr;
  }else{
    //注意下面括號(hào)里面都是other.m_data
    m_data = new char[strlen(other.m_data) + 1];
    strcpy(m_data, other.m_data);
  }
}
 
//析構(gòu)函數(shù)
String::~String(void)
{
  if(m_data != nullptr){
    delete [] m_data;
    m_data = nullptr;
  }
}
 
//賦值運(yùn)算符
String& String::operator=(const String& other)
{
  //判斷是否是給自己賦值
  if(this != other){
    delete [] m_data;  //先釋放掉原來的內(nèi)存
    if(other == nullptr){
      m_data = nullptr;
    }else{ 
      m_data = new char[strlen(other.m_data) + 1];
      strcpy(m_data, other.m_data);
    }
  }
  return *this;
}

另外兩個(gè)是重載+號(hào)和=號(hào)

String& operator + (String& other)
{
  char* tmp = m_data;
  m_data = new char[strlen(m_data) + strlen(other.m_data) + 1];
  strcpy(m_data, tmp);  //復(fù)制第一個(gè)字符串
  strcpy(m_data, other.m_data);  //復(fù)制第二個(gè)字符串
  delete [] tmp; //記得刪除這個(gè)內(nèi)存
  return *this;
}
 
String& operator = (String& other)
{
  if(this = other){
    return *this;
  }
  if(m_data != nullptr){
    delete [] m_data;  //先釋放之前的內(nèi)存
  }
  m_data = new char [strlen(other.m_data) + 1];
  strcpy(m_data, other.m_data);
  return *this;
}
 

以上所述是小編給大家介紹的c++編寫String類詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI