文字列クラスの実装:コンストラクション関数、コンストラクション関数、レプリケーションコンストラクション関数、および付与オペレータ

1964 ワード

いくつかのポイントを強調します.
(1)newオペレータがメモリの申請に失敗したのは、異常を投げ出したので、NULLを返すのではなく、失敗を申請してNULLを返すには、追加する必要がある(std::nothrow);
(2)std::nothrowを使用するにはヘッダファイル#includeが必要
(3)assertの使用
(4)コンストラクタにパラメータがある場合はデフォルトパラメータを付けるとデフォルトコンストラクタがありconstとして定義することを忘れない
(5)代入オペレータ関数体if文の条件はthis!=&otherでなければならないのに,なぜif(*this!=other)がだめなのか???
定義されたタイプはありません!=オペレータよ、どうやって比較できるのか、ポインタを比較するしかない...
#include
#include
#include
#include
#include
using namespace std;

class String
{
    private:
        char *m_data;

    public:
        String(const char *str = NULL);
        ~String();
        char * get_m_data() {return m_data;}
        String(const String&);
        String& operator= (const String &);
};

String::String(const char *str)
{
    if(str == NULL)
    {
        m_data = new (std::nothrow) char[1];
        assert(m_data != NULL);
        *m_data = '\0';
    }else
    {
        m_data = new (std::nothrow) char[strlen(str) + 1];
        assert(m_data != NULL);
        strcpy(m_data, str);
    }
}

String::~String()
{
    if(m_data != NULL)
    {
        delete []m_data;
        m_data = NULL;
    }
}

String::String(const String &other)
{
    m_data = new (std::nothrow) char[strlen(other.m_data) + 1];
    assert(m_data != NULL);
    strcpy(m_data, other.m_data);
}

String& String::operator= (const String &other)
{
    if(this != &other)
    {
        String tmp(other);
        char *str = tmp.m_data;
        tmp.m_data = m_data;
        m_data = str;
    }

    return *this;
}

int main()
{
    String s1("a big brother is watching you!!!");
    String s2(s1);
    //printf("haha
"); String s3; s3 = s1; printf("%s
", s1.get_m_data()); printf("%s
", s2.get_m_data()); printf("%s
", s3.get_m_data()); return 0; }