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

創新互聯建站是一家專業提供牟定企業網站建設,專注與成都網站建設、成都做網站、H5響應式網站、小程序制作等業務。10年已為牟定眾多企業、政府機構等服務。創新互聯專業網站設計公司優惠進行中。
編寫類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 的構造函數、拷貝構造函數、析構函數和賦值函數的實例,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
網站標題:詳解C++編寫String的構造函數、拷貝構造函數、析構函數和賦值函數
路徑分享:http://www.yijiale78.com/article26/ihdscg.html
成都網站建設公司_創新互聯,為您提供外貿建站、做網站、Google、網站改版、品牌網站建設、建站公司
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯