8.23-C++-作业

仿照string类,写一个my_string类

class my_string
{
private:
        char *str;
        int len;
publuc:
        //无参构造
        //有参构造
        //拷贝构造
        //拷贝赋值
        //bool my_empty() 判空
        //int my_size() 求长度
        //char *my_str() 转化为c风格字符串
}
要求:前四个必须实现,后三个尽力而为

#include <iostream>
#include <string.h>

using namespace std;
class my_string
{
private:
    char* str;
    int len;
public:
    //无参构造
    my_string()
    {
        this->str = new char[1]{'\0'};
        this->len = 0;
    }
    //有参构造
    my_string(char* str)
    {
        this->len = strlen(str);
        this->str = new char[(this->len)+1];
        strcpy(this->str,str);
    }
    //拷贝构造
    my_string(const my_string& O)
    {
        this->len = O.len;
        this->str = new char[O.len]{*(O.str)};
    }
    //拷贝赋值
    my_string& operator=(const my_string& R)
    {
        if(this!=&R)
        {
            this->len = R.len;
            this->str = new char[R.len]{*(R.str)};
        }
        return *this;
    }
    //bool my_empty() 判空
    bool my_empty()
    {
        return this->len==0?true:false;
    }
    //int my_size() 求长度
    int my_size()
    {
        return this->len;
    }
    //char *my_str() 转化为c风格字符串
    char *my_str()
    {
        return this->str;
    }
};

int main()
{
    my_string s0;
    cout<<"s0 size="<<s0.my_size()<<endl;

    my_string s1("abcdefg");
    cout<<"s1 size="<<s1.my_size()<<endl;

    my_string s2 = s1;
    cout<<"s2 size="<<s2.my_size()<<endl;

    my_string s3;
    s3 = s1;
    cout<<"s3 size="<<s3.my_size()<<endl;

    my_string s4 = "123";
    cout<<"s4 size="<<s4.my_size()<<endl;
    s4 = "45678";
    cout<<"s4 size="<<s4.my_size()<<endl;

    char* p = s1.my_str();
    cout<<p<<endl;

    cout << "Hello World!" << endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值