仿照string完成mystring类(拷贝构造、拷贝赋值)

该代码示例展示了如何在C++中自定义一个名为myString的类,模拟std::string的功能。类包含了无参构造、有参构造、显示函数、拷贝构造、拷贝赋值、析构函数、判空函数、size函数、c_str函数以及at函数。在main函数中,创建了myString对象并进行了操作,如对象间的赋值和方法调用。
摘要由CSDN通过智能技术生成
//仿照string完成mystring类

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

class myString
{
private:
    char *str;//记录c风格的字符串
    int size;//记录字符串的实际长度
public:
    //无参构造
    myString():size(10)
    {
        str = new char[size];
        cout<<"无参函数"<<endl;
    }
    //有参构造
    myString(const char *s)
    {
        size = strlen(s);
        str = new char[size+1];
        strcpy(str,s);
        cout<<"有参函数"<<endl;
    }
    //定义展示函数
    void show()
    {
        cout<<"size=  "<<size<<endl;
        cout<<"str=   "<<str<<endl;
    }
    //拷贝构造
    myString(const myString & other)
    {
        size = other.size;
        str = new char[size+1];
        strcpy(str,other.str);

        cout<<"拷贝构造函数"<<endl;
    }
    //拷贝赋值
    myString & operator = (const myString & other)
    {

        if(this != &other)//排除自己给自己赋值的情况
        {
            delete  []str;
            size = other.size;
            str = new char[size+1];
            strcpy(str,other.str);
        }
        return *this;
    }
    //析构函数
    ~myString()
    {
        cout<<"析构函数"<<endl;
        delete []str;//对指针空间进行释放
    }
    //判空函数
    bool empty()
    {
        if(size==0)
        {
            return  1;
        }
        else
            return 0;
    }

    //size函数
    int len()
    {
        return  size;
    }
    //c_str函数
    char *c_str()
    {
        return str;
    }

    //at函数
    char &at(int buf)
    {
        if(buf >0 && buf<= size)
        {
            return  str[buf];
        }
        else
            cout<<"输入错误"<<endl;
    }


};

int main()
{
    myString s1;//无参构造
    myString s2("abcde");//有参函数
    s2.show();
    myString s3(s2);//拷贝构造函数
    s3.show();

    //重定义一个新的类
    myString s4;
    if(s4.empty()!=0)
    {
        s4=s3;
    }
    cout<<"s4"<< s4.len ()<<endl;
    cout<<"s4.at(3)"<< s4.at(3) <<endl;
    


    return 0;
}

测试结果

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值