詳解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]; //對空字符串自動申請存放結(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ū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
c語言連接mysql數(shù)據(jù)庫的實現(xiàn)方法
C語言連接mysql數(shù)據(jù)庫,需要相應的頭文件和lib文件,如果你安裝Mysql數(shù)據(jù)庫,會在安裝目錄下找到這些庫文件,如果沒有安裝,也可以在網(wǎng)上找到2012-05-05
淺談C++中thread庫join和detach的區(qū)別
這篇文章主要為大家介紹了C++中thread庫join和detach的區(qū)別,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-11-11
static_cast,dynamic_cast,reinterpret_cast和const_cast的區(qū)別詳解
以下是對static_cast,dynamic_cast,reinterpret_cast和const_cast之間的區(qū)別進行了詳細的介紹,需要的朋友可以過來參考下2013-09-09

