仿照string类,写一个my_string类

#include <iostream>
#include <cstring>

using namespace std;
class my_string
{
private:
    char *str;
    int len;
public:
    //无参构造
    my_string(){};
    //有参构造
    my_string(char s,int l)
    {
        str=new char[l+1];
        for(int i=0;i<l;i++)
        {
            str[i]=s;
        }
        str[l]=0;
        len=l;
    }

    my_string(char *s)
    {
        len=strlen(s);
        str=new char[len+1];
        strcpy(str,s);
        str[len]=0;
    }

    //拷贝构造
    my_string(const my_string &o)
    {
        len=o.len;
        str=new char[o.len+1];
        for(int i=0;i<o.len+1;i++)
        {
            *(str+i)=*(o.str+i);
        }
        //*(o.str+len+1)=0;
    }

    //拷贝赋值
    my_string& operator=(const my_string &r)
    {
        //防止给自己赋值
        if(&r!=this)
        {
           len=r.len;
           if(str!=NULL)     //防止内存泄露
           {
               delete str;
               str=NULL;
           }
           str=new char[r.len+1];  //深拷贝
           for(int i=0;i<r.len+1;i++)
           {
               *(str+i)=*(r.str+i);
           }
           *(str+len+1)=0;
        }
        return *this;
    }

    void show()
    {
        cout<<"len="<<len<<"   str="<<str<<endl;
    }

    bool my_empty()
    {
        if(*str==0)
            return true;
        else
            return false;
    }

    int my_size()
    {
        return len;
    }

    //char *my_str()转化为c风格字符串
};

int main()
{
    my_string s1('h',4);
    my_string s2("string");
    my_string s3=s2;
    s1.show();
    s2.show();
    s3.show();

    s3=s1;
    s3.show();

    cout<< s3.my_empty()<<endl;
    cout<<s2.my_size()<<endl;
    cout<<s1.my_size()<<endl;
    cout << "Hello World!" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值