/*
Problem:编写MyString的构造函数、拷贝构造函数、析构函数和赋值函数
Author:QiZhao
Data:2018-02-04
Description:
Copyright  2018 QiZhao. All rights reserved.
*/
#include<cstring>
#include<iostream>
#include<cstdlib>

using namespace std;

class MyString
{
    public:
        MyString (const char *str = NULL);
        MyString (const MyString &other);
        ~ MyString(void);
        MyString & operator = (const MyString & other);
        friend ostream& operator<<(ostream &os, MyString &str);
    private:
        char *m_data;
};
//构造函数
MyString::MyString(const char *str)
{
    if(str == NULL)
    {
        m_data = new char[1];
        *m_data = '\0';
    }
    else
    {
        int len = strlen(str);
        m_data = new char[len + 1];
        if(m_data = NULL)
        {
            cout << "内存分配失败" << endl;
            exit(-1);
        }
        strcpy(m_data, str);
    }
    cout << "调用构造函数" << endl;
}
//拷贝构造函数
MyString::MyString(const MyString &other)
{
    int len = strlen(other.m_data);
    m_data = new char[len + 1];
    if(m_data = NULL)
    {
        cout << "内存分配失败" << endl;
        exit(-1);
    }
    strcpy(m_data, other.m_data);
    cout << "调用拷贝构造函数" << endl;
}
//析构函数
MyString::~MyString(void)
{
    delete[]m_data;
    m_data = NULL;
    cout << "调用析构函数" << endl;
}
//赋值函数
MyString& MyString::operator= (const MyString & other)
{
    if(this != &other)
    {
        delete[]m_data;
        int len = strlen(other.m_data);
        m_data = new char[len + 1];
        if(m_data = NULL)
        {
            cout << "内存分配失败" << endl;
            exit(-1);
        }
        strcpy(m_data, other.m_data);
    }
    return *this;
}
//输出
ostream& operator<<(ostream &os, MyString &str)
{
    os << str.m_data;
    return os;
}

int main()
{
    char str[] = "abcdef";
    char *p = NULL;

    cout << "**********************构造函数测试**********************" << endl;
    MyString test1(str);
    MyString test2(p);

    cout << "**********************拷贝构造函数测试**********************" << endl;
    MyString test(test1);

    cout << "**********************赋值函数测试**********************" << endl;
    cout << "调用前:" << endl;
    cout << test1 << endl;
    cout << test2 << endl;
    cout << "调用后:" << endl;
    test2 = test1;
    cout << test1 << endl;
    cout << test2 << endl;

    cout << "**********************析构函数测试**********************" << endl;
    return 0;
}