Mystring类

发布于:2023-01-21 ⋅ 阅读:(450) ⋅ 点赞:(0)

#include <iostream>
#include <cstring>
using namespace std;

class String
{
public:
    String(const char* str = NULL);
    String(const String &str);
    ~String();

    String& operator=(const String &str);
    String operator+(const String &str) const;
    String& operator+=(const String &str);
    char& operator[](int n) const;
    bool operator==(const String &str) const;
    friend ostream & operator<<(ostream &out, String &obj);
    int size() const;
    const char *c_str() const;

private:
    char *data;
    int m_size;
};

String::String(const char* str)
{
    if (!str)
    {
        m_size = 0;
        data = new char[1];
        *data = '\0';
    }
    else
    {
        m_size = strlen(str);
        data = new char[m_size + 1];
        strcpy(data, str);
    }
}


String::String(const String &str)
{
   m_size = str.size();
    data = new char[m_size + 1];
    strcpy(data, str.c_str());
}

String::~String()
{
    delete[] data;
    m_size = 0;
}

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

    delete[] data;
    
    m_size = str.size();
    data = new char[m_size + 1];
    strcpy(data, str.c_str());

    return *this;
}
String String::operator+(const String &str) const
{
    String newString;
    newString.m_size = m_size + str.size();
    newString.data = new char[newString.m_size + 1];
    strcpy(newString.data, data);
    strcat(newString.data, str.data);
    return newString;
}

String& String::operator+=(const String &str)
{
    m_size += str.size();
    char *newdata = new char[m_size + 1];
    strcpy(newdata, data);
    strcat(newdata, str.c_str());
    delete[] data;
    data = newdata;
    return *this;
}

char& String::operator[](int n) const
{
    if (n >= m_size) return data[m_size - 1];
    else return data[n];
}

bool String::operator==(const String &str) const
{
    if (m_size != str.size()) return false;
    return strcmp(data, str.c_str()) ? false : true;
}

int String::size() const
{
    return m_size;
}

const char *String::c_str() const
{
    return data;
}
ostream &operator<<(ostream &out, String & obj)
{
    
    out<<obj.data<<endl;

    return out;
}
int main()
{
    char a[] = "Hello", b[] = "World!";
    String s1(a), s2(b);
    cout << s1.c_str() << endl;
    cout << s2.c_str() << endl;
    s1 += s2;
    cout << s1.c_str() << endl;
    s1 = s2;
    cout << s1.c_str() << endl;
    cout << (s1 + s2).c_str() << endl;
    cout << s1.size() << endl;
    cout << s1[1] << endl;
    cout<<s1;
    if (s1 == s2)
        cout << "s1==s2" << endl;
}

本文含有隐藏内容,请 开通VIP 后查看