国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

詳解C++ 編寫String 的構造函數、拷貝構造函數、析構函數和賦值函數

2020-01-26 13:56:49
字體:
來源:轉載
供稿:網友

詳解C++ 編寫String 的構造函數、拷貝構造函數、析構函數和賦值函數

 編寫類String 的構造函數、析構函數和賦值函數,已知類String 的原型為:

class String{public:String(const char *str = NULL); // 普通構造函數String(const String &other); // 拷貝構造函數~ String(void); // 析構函數String & operate =(const String &other); // 賦值函數private:char *m_data; // 用于保存字符串}; 
#include <iostream> class String { public:   String(const char *str=NULL);//普通構造函數   String(const String &str);//拷貝構造函數   String & operator =(const String &str);//賦值函數   ~String();//析構函數 protected: private:   char* m_data;//用于保存字符串 };  //普通構造函數 String::String(const char *str){   if (str==NULL)  {     m_data=new char[1]; //對空字符串自動申請存放結束標志'/0'的空間     if (m_data==NULL)    {//內存是否申請成功      std::cout<<"申請內存失敗!"<<std::endl;      exit(1);     }     m_data[0]='/0';   }   else  {     int length=strlen(str);     m_data=new char[length+1];     if (m_data==NULL)    {//內存是否申請成功       std::cout<<"申請內存失敗!"<<std::endl;       exit(1);     }     strcpy(m_data,str);   } } //拷貝構造函數 String::String(const String &other){ //輸入參數為const型   int length=strlen(other.m_data);   m_data=new char[length+1];   if (m_data==NULL)  {//內存是否申請成功     std::cout<<"申請內存失敗!"<<std::endl;     exit(1);   }   strcpy(m_data,other.m_data); } //賦值函數 String& String::operator =(const String &other){//輸入參數為const型   if (this == &other) //檢查自賦值   { return *this; }  delete [] m_data;//釋放原來的內存資源   int length=strlen(other.m_data);     m_data= new char[length+1];   if (m_data==NULL)  {//內存是否申請成功     std::cout<<"申請內存失敗!"<<std::endl;     exit(1);   }   strcpy(m_data,other.m_data);   return *this;//返回本對象的引用 } //析構函數 String::~String(){   delete [] m_data; }  void main(){   String a;   String b("abc");   system("pause"); } 

以上就是C++ 編寫String 的構造函數、拷貝構造函數、析構函數和賦值函數的實例,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 龙州县| 信阳市| 二手房| 遂川县| 邹平县| 黎平县| 长丰县| 新平| 商都县| 北辰区| 白玉县| 报价| 谢通门县| 囊谦县| 临潭县| 大宁县| 修武县| 桐柏县| 松阳县| 会宁县| 乐都县| 中卫市| 正阳县| 延寿县| 顺义区| 呈贡县| 抚宁县| 简阳市| 松原市| 北安市| 黎川县| 岢岚县| 昭苏县| 德保县| 临朐县| 罗源县| 错那县| 德令哈市| 西乡县| 临夏市| 调兵山市|