欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊: 次

本文實(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{
    //注意下面括號里面都是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è)是重載+號和=號

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類詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對我們網(wǎng)站的支持!

上一篇:C++堆和棧的區(qū)別與聯(lián)系講解

欄    目:C語言

下一篇:用C/C++代碼檢測ip能否ping通(配合awk和system可以做到批量檢測)

本文標(biāo)題:c++編寫String類代碼實(shí)例

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/351.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有