2024.8.29 作业

仿照string类,实现myString

代码:

/*******************************************/

文件名:mystring.h

/*******************************************/

#include<cstring>
class MyString
{
private:
    char *str;
    int size;
public:
    //无参构造
    MyString():size(10)
    {
        str=new char[size];
        str[0] = '\0';
    }
    MyString(const char *s)
    {
        int lenth=strlen(s);
        str=new char[lenth];
        strcpy(str,s);
    }
    //判空函数
    bool empty()const;
    //size函数
    int c_size()const;
    //c_str函数
    const char *c_str();
    //at
    char &at(int index);
    //二倍扩容
    bool resize();
};

#endif // MYSTRING_H

/*******************************************/

文件名:mystring.cpp

/*******************************************/

#include"mystring.h"
//判空函数
bool MyString::empty()const
{
    if(size==0)
    {
        return 1;
    }
    return 0;
}
//size函数
int MyString::c_size()const
{
    return size;
}
//c_str函数
const char *MyString::c_str()
{
    return str;
}
//at
char &MyString::at(int index)
{
    return str[index];
}
//二倍扩容
bool MyString::resize()
{
    size*=2;
    char *temp=new char[size];
    strcpy(temp,str);
    delete[]str;
    str=temp;
    return 1;
}

/*******************************************/

文件名:work3.cpp

/*******************************************/

#include"mystring.h"

using namespace std;

int main()
{
    MyString s;
    MyString s2("hello world!");
    const char *c=s2.c_str();
    cout<<c<<endl;
    cout<<s2.at(2)<<endl;
    cout<<s.c_size()<<endl;
    s.resize();
    cout<<s.c_size()<<endl;
    return 0;
}

结果:

思维导图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值