12.6练习

1、模仿写一个My_string,功能和string差不多

#include <iostream>
#include <cstring>
using namespace std;

class My_string
{
private:
    char* cstr;
    int len;
public:
    My_string():cstr(NULL),len(0)//无参构造
    {
    }
    My_string(const char* str)//有参构造
    {
        len = strlen(str);
        cstr = new char[len+1]();
        strcpy(cstr,str);
    }
    My_string(const My_string &other)//拷贝构造
    {
 //       this->cstr = new char(*(other.cstr));//深拷贝
        this->len = other.len;
        cstr = new char[len+1]();
        strcpy(cstr,other.cstr);
    }
    ~My_string()//析构
    {
        delete cstr;//释放指针成员的空间
    }
    bool empty(){return (strlen(cstr) == 0 && len == 0);}//判空
    int size(){return len;}//返回长度
    char &at(int index){return cstr[index];}//定位
    char* c_str(){return cstr;}//传化为C风格字符串
};

int main()
{
    My_string s1;
    cout<<s1.empty()<<endl;
    My_string s2("my hello");
    cout<<s2.empty()<<endl;
    cout<<s2.size()<<endl;
    cout<<s2.at(4)<<endl;
    char* str = s2.c_str();
    cout<<str<<endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值