天天看點

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

C++預設的拷貝構造函數和指派構造函數都是淺拷貝,是以當遇到類成員含有指針變量時,就得自己實作深拷貝!

const string& other 可以通路私有變量?

編寫類String 的構造函數、析構函數和指派函數,已知類String 的原型為:

class String

{

public:

   String(const char *str=NULL);//普通構造函數

   String(const String &str);//拷貝構造函數

   String & operator =(const String &str);//指派函數

   ~String();//析構函數

private:

   char* m_data;//用于儲存字元串

};

答:

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
 
class String
{
public:
    String(const char *str=NULL);//普通構造函數
    String(const String &str);//拷貝構造函數
    String & operator =(const String &str);//指派函數
    ~String();//析構函數
 
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;
}
 
int main()
{
    String a;
    String b("abc");
    a = b;
    system("pause");
}

      

繼續閱讀