String类的实现

#include <iostream>
using namespace std;

class String
{
public:
    String(const char *p = nullptr)
    {
        if (p != nullptr)
        {
            _pstr = new char[strlen(p) + 1];
            strcpy(_pstr, p);
        }
        else
        {
            _pstr = new char[1];
            *_pstr = '\0';
        }
    }
    ~String()
    {
        delete[]_pstr;
        _pstr = nullptr;
    }
    String(const String &str)
    {
        _pstr = new char[strlen(str._pstr) + 1];
        strcpy(_pstr, str._pstr);
    }
    String& operator=(const String &str)
    {
        if (this == &str)
        {
            return *this;
        }
        delete[]_pstr;
        _pstr = new char[strlen(str._pstr) + 1];
        strcpy(_pstr, str._pstr);
        return *this;
    }
    bool operator>(const String &str)const
    {
        return strcmp(_pstr, str._pstr)>0;
    }
    bool operator<(const String &str)const
    {
        return strcmp(_pstr, str._pstr)<0;
    }
    bool operator==(const String &str)const
    {
        return strcmp(_pstr, str._pstr) == 0;
    }
   
    int length()const
    {
        return strlen(_pstr);
    }
    char& operator[](int index)
    {
        return _pstr[index];
    }
    const char& operator[](int index)const
    {
        return _pstr[index];
    }
    const char* c_str()const
    {
        return _pstr;
    }
    friend ostream& operator<<(ostream &out, const String &str);
    friend String operator+(const String &lhs, const String &rhs);
private:
    char *_pstr;
};

String operator+(const String &lhs, const String &rhs)
{
  /*  char *ptmp = new char[strlen(lhs._pstr) + strlen(rhs._pstr)+1];*/
    String tmp;
    tmp._pstr = new char[strlen(lhs._pstr) + strlen(rhs._pstr) + 1];
    strcpy(tmp._pstr,lhs._pstr);
    strcat(tmp._pstr, rhs._pstr);

    //delete[]ptmp;
    return tmp;
}
ostream& operator<<(ostream &out, const String &str)
{
    out << str._pstr;
    return out;
}
int main()
{
    String str1;
    String str2 = "aaa";
    String str3 = "bbb";
    String str4 = str2 + str3;
    String str5 = str2 + "ccc";
    String str6 = "ddd" + str2;
    cout << "str6: " << str6 << endl;
    if (str5 > str6)
    {
        cout << str5 << ">" << str6 << endl;
    }
    else
    {
        cout << str5 << "<" << str6 << endl;
    }
    int len = str6.length();
    for (int i = 0; i < len; i++)
    {
        cout << str6[i];
    }
    cout << endl;
    char buf[1024] = { 0 };
    strcpy(buf, str6.c_str());
    cout << "buf: " << buf << endl;
}

运行结果;
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值