C++: day4

1.封装mystring类

#include <iostream>
#include <cstring>

using namespace std;

class Mystring
{
private:
    char *str;      //记录c风格字符串
    int sizes;       //记录字符串的实际长度

public:
    Mystring():sizes(10)      //无参构造
    {
        str = new char[sizes];       //默认设置10字节
        strcpy(str, "");        //初始化为空串
    }

    Mystring(const char *s)     //有参构造
    {
        sizes = strlen(s);       //字符串长度
        str = new char[sizes+1];     //最后\0算上
        strcpy(str, s);     //字符串复制
    }

    ~Mystring()     //析构函数
    {
        delete []str;       //释放指针指向空间
    }

    Mystring (const Mystring &other)        //拷贝构造函数
    {
        sizes = other.sizes;
        str = new char[sizes+1];
        strcpy(str, other.str);
    }

    Mystring &operator=(const Mystring &other)      //拷贝赋值函数
    {
        delete this;
        sizes = other.sizes;
        this->str = new char[sizes+1];
        strcpy(str, other.str);

        return *this;
    }

    bool empty()        //判空函数
    {
        if (sizes == 0)
            return true;
        else
            return false;
    }

    int size()      //size函数
    {
        return sizes;
    }

    const char *c_str()       //c_str函数
    {
        return str;
    }

    char &at(int pos)       //at()函数
    {
        if(pos >= sizes || pos < 0)
        {
            cout << "下标不合法" <<endl;
        }
        return str[pos];
    }

    const Mystring operator+(const Mystring &R)const    //成员函数实现+
    {
        Mystring temp;
        delete temp;
        temp.sizes = this->sizes + R.sizes;
        temp.str = new char[temp.size];
        
        temp.str = strcat(this->str, R.str);
      
        return temp;
    }

    Mystring &operator+=(const Mystring &R)      //成员函数实现+=
    {
        strcat(this->str, R.str);
        this->sizes = this->sizes + R.sizes;

        return *this;
    }

    bool operator>(const Mystring &R)const      //成员函数实现>
    {
        if(strcmp(this->str, R.str))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};



int main()
{
    Mystring s1;        //无参构造
    Mystring s2("hello");       //有参构造
    s1 = s2;       //拷贝赋值函数
    //        Mystring s1 = s2;        //拷贝构造函数
//    Mystring s1;
    s1 += s2;


    if (s1.empty())     //判空
        cout << "空" <<endl;

    cout << "s1.size = " << s1.size() <<endl;      //size函数

    cout << "s1 = " << s1.c_str() <<endl;       //c_str函数

    cout << "s1[1] = " << s1.at(1) <<endl;       //at()函数

    if (s1 > s2)
        cout << "s1 > s2" <<endl;
    
    return 0;
}

 2.思维导图

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lin---

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值