編寫類String 的建構函式、拷貝建構函式、解構函式和賦值函式
阿新 • • 發佈:2019-01-02
編寫類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(constchar *str=NULL);//普通建構函式
- String(const String &str);//拷貝建構函式
- String & operator =(const String &str);//賦值函式
- ~String();//解構函式
- protected:
- private:
- char* m_data;//用於儲存字串
- };
- //普通建構函式
- String::String(constchar *str)
- {
- if (str==NULL)
- {
-
m_data=new
- if (m_data==NULL)
- {//記憶體是否申請成功
- std::cout<<"申請記憶體失敗!"<<std::endl;
- exit(1);
- }
- m_data[0]='\0';
- }
- else
- {
- int length=strlen(str);
- m_data=newchar[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=newchar[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= newchar[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");
- }