2024.9.2

还没写完 

#include 
#include 
using namespace std;

class myString
{
private:
    char *str;          //字符串
    int size;           //实际字符长度
    int len;            //字符串容量
public:
    myString():size(10)     //无参构造函数
    {
        len = size + 1;
        str = new char[size];
    }
    myString(const char*s):size(strlen(s))      //有参构造函数
    {
        //cout< size || index < 0)       //判断是否下标越界
    {
        cout<<"下标越界"<= len)       //判断是否需要二倍扩容
    {
        expand();
    }
    str[size] = s;
    size++;
    str[size] = '\0';
}
//尾删一个字符
void myString::pop_back()
{
    str[size-1] = 0;
    size--;
}
//+=
myString & myString::operator+=(const myString &R)
{
    while(size + int(strlen(R.str)) >= len)
    {
        expand();
    }
    strcat(this->str,R.str);
    return *this;
}
//二倍扩容
void myString::expand()
{
    len = len * 2 - 1;
    char*newstr = new char[len];
    memset(newstr,0,len);
    strcpy(newstr,str);
    delete []str;
    str = newstr;
}
//+
myString &myString::operator+(const myString &R)        //两个字符串相加
{
    while((size + R.size) >= len)
    {
        expand();
    }
    strcat(str,R.str);
    size = size + R.size;
    return *this;
}
myString &myString::operator+(const char &R)        //字符串和单个字符相加
{
    if(size + 1 >= len)
    {
        expand();
    }
    push_back(R);
    return *this;
}
int main()
{
    myString s1("nihao");
    myString s2("hello world");
    s1 = s2;
    s1.show();
    cout<

2024.9.2_第1张图片

你可能感兴趣的:(c++,算法,开发语言)