仿照string类,封装一个My_string类,并实现相关功能

要求:

//无参构造默认长度为15

//有参构造

//析构函数

//拷贝构造函数

//拷贝赋值函数

//c_str函数

//size函数

//empty函数

//at函数

总代码如下:

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

class My_string
{
private:
    char *data;
    int len;
public:
    //无参构造默认长度为15
     My_string():len(15)
     {
         data = new char[len];
         data[0] = '\0';

     }

     //有参构造
     My_string(const char *str)
     {
            len = strlen(str);
            data = new char[len+1];

            strcpy(data,str);
     }

     My_string(int n, char ch)
     {
         len = n;
         data = new char[n+1];
         for(int i = 0; i < n; i++)
                data[i] = ch;
     }

     //析构函数
     ~My_string()
     {
         delete []data;
         cout<<"析构函数"<<"    this = "<<this<<endl;

     }

     //拷贝构造函数
     My_string(const My_string &str ):data(str.data)
     {
            data = new char[str.len+1];
            strcpy(data,str.data);
     }

     //拷贝赋值函数
     My_string & operator=(const My_string &str)
     {
         if(this!=&str){
             data=new char[str.len+1];
             strcpy(data,str.data);
             len=str.len;
         }
         return *this;
     }

     //c_str函数
     char *c_str()
     {
         return data;
     }

     //len函数
     int size()
     {
         return len;
     }

     //empty函数
     bool empty()  //判断是否为空
     {
         if(len==0)
         {
             return 0;
         }
         else
         {
             return 1;
         }
     }

     //at函数
     char at(int n)
     {
         return *(data+n);
     }


     void show()
     {
         cout<<data<<endl;
     }
};

int main()
{
    My_string s("hello world");
    s.show();

    My_string s2(5,'b');
    s2.show();

    My_string s3 = s2;
    s3.show();

    My_string s4;
    s4 = s;
    s4.show();
    cout<<"s4长度为"<<s4.size()<<endl;
    if(s4.empty())
    {
        cout<<"s4不空"<<endl;
    }
    else
    {
        cout<<"s4空"<<endl;
    }
    cout<<"s4[1] = "<<s4.at(1)<<endl;


    return 0;
}

结果如图所示:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值