9月2日作业

仿写几个String类函数

#include <iostream>
#include <cstring>

using namespace std;

class mystring
{
    public:
        //无参构造函数
        mystring()
        {
            str = nullptr;
            len = 0;
        }
        //有参构造函数
        mystring(const char *s)
        {
            len = strlen(s);
            str = new char[len + 1];
            strcpy(str, s);
        }
        //拷贝构造函数
        mystring(const mystring &other)
        {
            len = other.len;
            str = new char[len + 1];
            strcpy(str, other.str);
        }
        //拷贝赋值函数
        mystring & operator = (const mystring &other)
        {
            if(&other != this)
            {
                len = other.len;
                if(str == nullptr)
                {
                    str = new char[len + 1];
                }
                else
                {
                    delete []str;
                    str = nullptr;
                }
                strcpy(str, other.str);
            }
            return *this;
        }
        ~mystring()
        {
            if(str != nullptr)
            {
                delete []str;
                str = nullptr;
            }
        }
        char *data()
        {
            return str;
        }

        int size()
        {
            return len;
        }

        bool empty()
        {
            if(len != 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        char& at(int index)
        {
            if(index >=0 && index <= len - 1)                                                           
            {
                return str[index];
            }
            else
            {
                cout << "下标超出范围" << endl;
                return str[0];
            }
        }
    private:
        char *str;
        int len;
};

int main(int argc, const char *argv[])
{
    mystring s1("hello world");
    cout << s1.data() << endl;
    cout << s1.size() << endl;
    cout << s1.empty() << endl;
    cout << s1.at(4) << endl;
    return 0;
}
                                                                                                        

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值