美文网首页
实现string类

实现string类

作者: 狗尾巴草败了 | 来源:发表于2017-09-18 12:20 被阅读0次
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

class String {
    String(const char* str = NULL);
    ~String();
    String(const String& other);
    String& operator= (const String& other);
    String& operator= (const char* str);
    inline char* c_str() const {
        return m_data;
    }
private:
    char* m_data;
};

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

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

String::String(const String& other) {
    int len = strlen(other.m_data);
    m_data = new char[len+1];
    strcpy(m_data, other.m_data);
}

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

    delete[] m_data;
    int len = strlen(other.m_data);
    m_data = new char[len+1];
    strcpy(m_data, other.m_data);
    return *this;
}

String& String::operator=(const char *str) {
    delete[] m_data;
    int len = strlen(str);
    m_data = new char[len+1];
    strcpy(m_data, str);
}

相关文章

网友评论

      本文标题:实现string类

      本文链接:https://www.haomeiwen.com/subject/qszvsxtx.html