溫馨提示×

溫馨提示×

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

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

怎么使用C++實現(xiàn)String類

發(fā)布時間:2021-04-14 11:01:45 來源:億速云 閱讀:194 作者:小新 欄目:編程語言

小編給大家分享一下怎么使用C++實現(xiàn)String類,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

C++實現(xiàn)String類實例代碼

這是一道十分經(jīng)典的面試題,可以短時間內(nèi)考查學(xué)生對C++的掌握是否全面,答案要包括C++類的多數(shù)知識,保證編寫的String類可以完成賦值、拷貝、定義變量等功能。

#include<iostream> 
using namespace std; 
 
class String 
{ 
public: 
    String(const char *str=NULL); 
    String(const String &other); 
    ~String(void); 
    String &operator =(const String &other); 
private: 
    char *m_data; 
}; 
 
String::String(const char *str) 
{ 
  cout<<"構(gòu)造函數(shù)被調(diào)用了"<<endl; 
  if(str==NULL)//避免出現(xiàn)野指針,如String b;如果沒有這句話,就會出現(xiàn)野 
         //指針 
  { 
    m_data=new char[1]; 
    *m_data=''/0''; 
  } 
  else 
  { 
   int length=strlen(str); 
   m_data=new char[length+1]; 
   strcpy(m_data,str); 
  } 
} 
String::~String(void) 
{ 
  delete m_data; 
  cout<<"析構(gòu)函數(shù)被調(diào)用了"<<endl; 
} 
 
String::String(const String &other) 
{ 
 cout<<"賦值構(gòu)造函被調(diào)用了"<<endl; 
 int length=strlen(other.m_data); 
 m_data=new char[length+1]; 
 strcpy(m_data,other.m_data); 
} 
String &String::operator=(const String &other) 
{ 
   cout<<"賦值函數(shù)被調(diào)用了"<<endl; 
   if(this==&other)//自己拷貝自己就不用拷貝了 
         return *this; 
   delete m_data;//刪除被賦值對象中指針變量指向的前一個內(nèi)存空間,避免 
          //內(nèi)存泄漏 
   int length=strlen(other.m_data);//計算長度 
   m_data=new char[length+1];//申請空間 
   strcpy(m_data,other.m_data);//拷貝 
   return *this; 
} 
void main() 
{ 
   String b;//調(diào)用構(gòu)造函數(shù) 
   String a("Hello");//調(diào)用構(gòu)造函數(shù) 
   String c("World");//調(diào)用構(gòu)造函數(shù) 
   String d=a;//調(diào)用賦值構(gòu)造函數(shù),因為是在d對象建立的過程中用a來初始化 
   d=c;//調(diào)用重載后的賦值函數(shù) 
}

以上是“怎么使用C++實現(xiàn)String類”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

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

AI