仿照string类,写一个my_string类

#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
    char* str;
    int len;

public:
    //无参构造
    my_string()
    {
        memset(this, 0, sizeof(my_string));//全部清0
        cout<<"无参构造"<<endl;
    }
    //析构函数
    ~my_string()
    {
        delete [] this->str;
        str = nullptr;
        cout<<"析构函数"<<endl;
    }

    //有参构造
    my_string(char* str, int len)
    {
        this->str = new char[128];//开辟空间
        memcpy(this->str, str, len);//拷贝内容
        this->len = len;
        cout<<"有参构造"<<endl;
    }

    //拷贝构造
    my_string(const my_string& other)
    {
        this->str = new char[128];
        memcpy(this->str, other.str, other.len);
        this->len = other.len;
        cout<<"深拷贝"<<endl;
    }

    //拷贝赋值
    my_string& operator = (const my_string& other)//两个对象已经存在,只能赋值不能初始化
    {
        if(this==&other)//防止自己给自己赋值
        {
            return *this;
        }
        if(this->str != nullptr)//已经指向堆区空间
        {
            delete []str;//释放原有空间,避免内存泄露
            this->str = new char[128];//重新开辟空间
        }else//使用无参构造创建出来的对象,指针没有指向堆区空间
        {
            this->str = new char[128];//开辟空间
        }
        memcpy(this->str, other.str, other.len);//拷贝内容
        this->len = other.len;
        cout<<"拷贝赋值"<<endl;
        return *this;
    }

    //判空
    bool my_empty()
    {
        return this->str[0]==0? true:false;
    }
    //求长度
    int my_size()
    {
        int i = 0;
        while(this->str[i] != 0)
        {
            i++;
        }
        return i;
    }
    void show()
    {
        cout<<this->str<<'\t'<<this->len<<endl;
    }

};
int main()
{
    char buff[]="12345678";
    my_string s1(buff, sizeof(buff));
    s1.show();
    my_string s2 = s1;
    s2.show();
    my_string s3;
    s3.operator =(s2);
    s3.show();
    cout<< "1为空,0为非空: "<<s3.my_empty()<<endl;
    cout<<"字符串实际长度: "<<s3.my_size()<<endl;
    return 0;
}

测试结果:

有参构造
12345678        9
深拷贝
12345678        9
无参构造
拷贝赋值
12345678        9
1为空,0为非空: 0
字符串实际长度: 8
析构函数
析构函数
析构函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

傾语

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

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

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

打赏作者

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

抵扣说明:

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

余额充值