封装一个My_string类

1.作业需求:仿照string类,封装一个My_string类,并实现相关功能

实现过程:

#include <iostream>
#include <cstring>

using namespace std;

class my_string
{
private:
    char *date;
    int  size;
public:
    my_string():size(15)
    {
        date = new char [size];
        date[0]='\0';
        cout<<"无参构造完成"<<endl;
    }

    my_string(const char *str)
    {
        size=sizeof (str);
        date = new char[size];
        strcpy(date,str);
        cout<<"有参构造完成"<<endl;

    }

    my_string(int n,  char ch)
    {
        size=n*sizeof(ch);
        date = new char[size];
        for(int i=0;i<n;i++)
        {
            date[i]=ch;
        }
        cout<<"多参构造完成"<<endl;
    }

    ~my_string()
    {
        delete date;
        cout<<"析构函数完成"<<endl;
    }

    my_string(const my_string &s)
    {
        this->size=s.size;
        this->date=new char[this->size];
        strcpy(this->date,s.date);
        cout<<"拷贝构造函数"<<endl;
    }

    my_string & operator=(const my_string &s)
    {
        this->size=s.size;
        this->date=new char[this->size];
        strcpy(this->date,s.date);
        cout <<"拷贝赋值函数"<<endl;
        return *this;
    }

    const char *c_str()
    {
        return date;
    }

    int my_size()
    {
        return size;
    }

    bool empty()
    {
        return strlen(date);
    }

    char at(int n)
    {
        if(n<0 ||n >size-1)
        {
            cout<<"数值越界"<<endl;
            return 0;
        }
        return date[n];
    }



    void show()
    {
        cout<<"date = "<<date<<endl;
    }

};

int main()
{
    string s("hello");
    cout<<"s = "<<s<<endl;
    my_string s1("hello");

    s1.show();
    if(s1.empty())
    {
        cout<<"s1字符串不为空"<<endl;
    }else
    {
        cout<<"s1字符串为空"<<endl;
    }

    cout<<"s1.at = "<<s1.at(0)<<endl;
    s1.show();
    my_string s2(5,'A');
    s2.show();
    s2.show();
    cout<<"s2size = "<<s2.my_size()<<endl;
    if(s2.empty())
    {
        cout<<"s2字符串不为空"<<endl;
    }else
    {
        cout<<"s2字符串为空"<<endl;
    }
    my_string s3;
    if(s3.empty())
    {
        cout<<"s3字符串不为空"<<endl;
    }else
    {
        cout<<"s3字符串为空"<<endl;
    }
    my_string s4=s1;
    s4.show();
    my_string s5;
    s5=s1;
    s5.show();

    return 0;
}

实验结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值