22081-11-4 仿照string类,写一个my_string类

本文介绍了一个简单的C++自定义字符串类my_string的实现,包括无参构造、有参构造、拷贝构造和赋值操作等核心功能,并演示了如何使用该类创建和操作字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

仿照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>
using namespace std;
class my_string
{
private:
    char *str;
    int len;
public:
    my_string(){}//无参构造函数
    ~my_string(){}//析构函数
    my_string(char *p)//有参构造函数
    {
        len=my_size(p);
        str=new char[len];
        for(int i=0;i<len;i++)
        {
            str[i]=*(p+i);
        }
    }
     my_string(my_string& s)//拷贝构造函数
          {
              this->len=s.len;
              str=new char[len];
              for(int i=0;i<len;i++)
              {
                  str[i]=s.str[i];
              }
          }
      my_string& operator=(my_string &R)
      {
          this->len=R.len;
          this->str=new char[len];
          for(int i=0;i<len;i++)
          {
              str[i]=R.str[i];
          }
          return *this;
      }

    void show()
    {
       cout<<"str="<<this->str<<endl;
    }
    //长度
    int my_size(char *s)
    {
        int len=0;
        while(*s!='\0')
        {
            len++;
            s++;
        }
        return len+1;
    }
    //判空
    bool my_empty()
    {
      return len==0?true:false;
    }
};

int main()
{
    my_string s1("hqykj");
    s1.show();
    my_string s2(s1);
    s2.show();
    my_string s3;
    s3=s2;
    s3.show();
    if(s1.my_empty()==true)
    {
        cout<<"null"<<endl;
    }
    else
    {
        cout<<"full"<<endl;
    }
    cout << "Hello World!" << endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值