詳解C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)
創(chuàng)新互聯(lián)建站是一家專業(yè)提供牟定企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站建設(shè)、成都做網(wǎng)站、H5響應(yīng)式網(wǎng)站、小程序制作等業(yè)務(wù)。10年已為牟定眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計公司優(yōu)惠進行中。
編寫類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]; //對空字符串自動申請存放結(jié)束標志'\0'的空間 if (m_data==NULL) {//內(nèi)存是否申請成功 std::cout<<"申請內(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)存是否申請成功 std::cout<<"申請內(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)存是否申請成功 std::cout<<"申請內(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)存是否申請成功 std::cout<<"申請內(nèi)存失?。?<<std::endl; exit(1); } strcpy(m_data,other.m_data); return *this;//返回本對象的引用 } //析構(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ù)的實例,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
網(wǎng)站標題:詳解C++編寫String的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)
路徑分享:http://muchs.cn/article26/ihdscg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、做網(wǎng)站、Google、網(wǎng)站改版、品牌網(wǎng)站建設(shè)、建站公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)