詳解C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)
詳解C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)
編寫類String 的構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù),已知類String 的原型為:
class String { public: String(const char *str = NULL); // 普通構(gòu)造函數(shù) String(const String &other); // 拷貝構(gòu)造函數(shù) ~ String(void); // 析構(gòu)函數(shù) String & operate =(const String &other); // 賦值函數(shù) private: char *m_data; // 用于保存字符串 };
#include <iostream> class String { public: String(const char *str=NULL);//普通構(gòu)造函數(shù) String(const String &str);//拷貝構(gòu)造函數(shù) String & operator =(const String &str);//賦值函數(shù) ~String();//析構(gòu)函數(shù) protected: private: char* m_data;//用于保存字符串 }; //普通構(gòu)造函數(shù) String::String(const char *str) { if (str==NULL) { m_data=new char[1]; //對(duì)空字符串自動(dòng)申請(qǐng)存放結(jié)束標(biāo)志'\0'的空間 if (m_data==NULL) {//內(nèi)存是否申請(qǐng)成功 std::cout<<"申請(qǐng)內(nèi)存失?。?<<std::endl; exit(1); } m_data[0]='\0'; } else { int length=strlen(str); m_data=new char[length+1]; if (m_data==NULL) {//內(nèi)存是否申請(qǐng)成功 std::cout<<"申請(qǐng)內(nèi)存失敗!"<<std::endl; exit(1); } strcpy(m_data,str); } } //拷貝構(gòu)造函數(shù) String::String(const String &other) { //輸入?yún)?shù)為const型 int length=strlen(other.m_data); m_data=new char[length+1]; if (m_data==NULL) {//內(nèi)存是否申請(qǐng)成功 std::cout<<"申請(qǐng)內(nèi)存失?。?<<std::endl; exit(1); } strcpy(m_data,other.m_data); } //賦值函數(shù) String& String::operator =(const String &other) {//輸入?yún)?shù)為const型 if (this == &other) //檢查自賦值 { return *this; } delete [] m_data;//釋放原來的內(nèi)存資源 int length=strlen(other.m_data); m_data= new char[length+1]; if (m_data==NULL) {//內(nèi)存是否申請(qǐng)成功 std::cout<<"申請(qǐng)內(nèi)存失??!"<<std::endl; exit(1); } strcpy(m_data,other.m_data); return *this;//返回本對(duì)象的引用 } //析構(gòu)函數(shù) String::~String() { delete [] m_data; } void main() { String a; String b("abc"); system("pause"); }
以上就是C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)的實(shí)例,如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
C++計(jì)算整數(shù)序列的最長(zhǎng)遞增子序列的長(zhǎng)度操作
這篇文章主要介紹了C++計(jì)算整數(shù)序列的最長(zhǎng)遞增子序列的長(zhǎng)度操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12C語言完整實(shí)現(xiàn)12種排序算法(小結(jié))
本文主要介紹了C語言完整實(shí)現(xiàn)12種排序算法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05深入探究C/C++中互斥量(鎖)的實(shí)現(xiàn)原理
? 互斥量是一種同步原語,用于保護(hù)多個(gè)線程同時(shí)訪問共享數(shù)據(jù),互斥量提供獨(dú)占的、非遞歸的所有權(quán)語義,本文將和大家一起深入探究C/C++中互斥量(鎖)的實(shí)現(xiàn)原理,感興趣的小伙伴跟著小編一起來看看吧2024-06-06C++實(shí)現(xiàn)LeetCode(120.三角形)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(120.三角形),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07