詳解C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)
更新時間:2017年08月28日 09:38:56 作者:愛思考的小鳥
這篇文章主要介紹了詳解C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)的相關(guān)資料,這里提供實例幫助大家理解掌握這部分內(nèi)容,需要的朋友可以參考下
詳解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ū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

