詳解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 的構造函數、拷貝構造函數、析構函數和賦值函數的實例,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選