2022.12.6---封装c++中的string

仿照string类,实现自定义My_strng类,以及相关操作:
定义私有成员变量,字符串及其长度,定义无参构造函数,有参构造函数,拷贝构造函数,析构函数,定义一些成员函数,判断字符串是否为空,求字符串长度,访问指定位置的字符,转换为c风格的字符串。
#include <iostream>
#include<cstring>

using namespace std;

class my_string
{
private:
    char *cstr;
    int len;
public:
    my_string():cstr(NULL),len(0) {cout<<"无参构造"<<endl;}  //无参构造函数
    my_string(const char *str)    //有参构造函数
    {
        this->len=strlen(str);
        this->cstr=new char[this->len];
        strcpy(this->cstr,str);
        cout<<"有参构造"<<endl;
    }
    my_string(const my_string &other)    //拷贝构造函数
    {
        this->len=other.len;
        this->cstr=new char[this->len];
        strcpy(this->cstr,other.cstr);
        cout<<"拷贝构造"<<endl;
    }
    ~my_string()    //析构函数
    {
        if(this->cstr!=NULL)
        {
            delete this->cstr;
        }
        cout<<"析构函数"<<endl;
    }
    bool empty()   //判断是否为空
    {
        if(this->len)
        {
            cout<<"字符串不为空"<<endl;
            return 1;
        }
        else
        {
            cout<<"字符串为空"<<endl;
            return 0;
        }
    }
    int size()   //返回字符串的长度
    {
        return this->len;
    }
    char &at(int index)   //定位函数
    {
        for(int j=0;j<this->len;j++)
        {
            if(j==index-1)
                break;
        }
        return this->cstr[index-1];
    }
    char *c_str()   //转化为c风格字符串
    {
        return this->cstr;
    }
};

int main()
{
    my_string s;                        //s调用无参构造
    cout<<"s:";
    s.empty();                          //s判空
    my_string s1("helloya");            //s1调用有参构造
    cout<<"s1:";
    s1.empty();                         //s1判空
    cout<<"s1.size="<<s1.size()<<endl;  //求s1长度
    cout<<"s1.at(5)="<<s1.at(5)<<endl;  //访问s1指定位置字符
    my_string s2(s1);                   //s2调用拷贝构造
    cout<<"s2.size="<<s2.size()<<endl;  //求s2长度
    cout<<"s2.at(2)="<<s2.at(2)<<endl;  //访问s2指定位置字符
    printf("s1=%s\n",s1.c_str());       //s1转化为c风格字符串
    return 0;
}

Xmind导图

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值