自己实现一个 String 类

 

C++面试常被问到的题目

#include <iostream>
#include <string>
#include <string.h>
using namespace std;

class Mystring 
{
    public:
        Mystring (const char*str = NULL);
        ~Mystring (void);
        Mystring (const Mystring &other);
        Mystring & operator = (const Mystring &other);
        char *getM_data(void);
  private:
        char *m_data;
};

Mystring::Mystring(const char *str)
{
  if (str == NULL)
    {
         if(m_data != NULL)
         {
             delete[] m_data;
         }
         m_data = new char[1];
         *m_data = '\0';
    }
    else
    {
        int length = strlen(str);
        if(m_data != NULL)
        {
          delete[] m_data;
        }
        m_data = new char[length+1];
        strcpy(m_data, str);
    }
}

Mystring::~Mystring()
{
    delete[] m_data;
}


Mystring::Mystring(const Mystring &other)
{
    int length = strlen(other.m_data);
    if(m_data == NULL)
    {
        delete[] m_data;
    }
    m_data = new char[length+1];

    strcpy(m_data, other.m_data);
}

Mystring& Mystring::operator=(const Mystring& other)
{
    if(this == &other)
    {
        return *this;
    }

    delete[] m_data;

    int length = strlen(other.m_data);
    m_data = new char[length+1];
    strcpy(m_data, other.m_data);

    return *this;
}

char *Mystring::getM_data()
{
    return m_data;
}


int main()
{
    Mystring s1("hello");
    cout << "s1 m_data:" << s1.getM_data() << endl;

    // test copy 
    Mystring s2 = s1;
    cout << "s2 m_data:" << s2.getM_data() << endl;


    // test operator =
    Mystring s3;
    s3 = s1;
    cout << "s3 m_data:" << s3.getM_data() << endl;

    return 0;
}

 

上一篇:【JS】我的JavaScript学习之路(6)


下一篇:关于C++的继承与派生