模拟string类的运算符重载(未实现)

文章定义了一个名为mystring的类,该类模拟了标准库中的string。类中包含了构造函数(默认和接受字符串长度、字符数组的构造函数)、拷贝构造函数、赋值运算符重载、加法运算符重载以及比较运算符重载。在main函数中展示了如何创建和使用mystring对象。
摘要由CSDN通过智能技术生成

代码如下:

#include <iostream>
#include <string.h>
using namespace std;

class mystring
{
public:
    int size=20;
    char *str;
    mystring(){};
    mystring(int size):str(new char(size)+1)
    {
        cout << "构造函数" << endl;
    };

    mystring(char *buf)
    {
        this->size = strlen(buf);
        str = new char(size);
        strcpy(str,buf);
    }

    mystring(mystring &s):size(s.size)
    {
        cout<<"s2中的字符串大小为" <<this->size <<endl;
        this->str = new char(size);
        strcpy(this->str,s.str);
        cout << "拷贝完毕 " <<endl;
    }
    
    const mystring operator= ( const mystring &buf )const
    {
        mystring s1;
        
        s1.size = this->size;
        s1.str = this->str;
        return s1;
    }
    
    const mystring operator+(const mystring &buf)const
    {
        mystring s1;
        s1.size +=buf.size;
        strcpy(s1.str,buf.str);
        return  s1;
    }

    bool operator>(const mystring &buf)const
    {   
        return  (this->size > buf.size);
    }
    
    bool operator<(const mystring &buf)const
    {
 
        return   (this->size < buf.size);
    }    
    
    ~mystring()
    {
        delete str;
        cout <<"析构完毕 "<<endl;
    }
    



};

int main()
{
    //cout << "Hello World!" << endl;
    //封装string
    char buf[20];
    cin >> buf;
    cout << "s1中的字符串内容为" << buf <<endl;
    int size = strlen(buf);     //字符串大小
    cout <<"s1中的字符串大小为" << size <<endl;
    mystring s1(buf);
    mystring s2 = s1;
    cout << "s2中的字符串内容为" << s2.str <<endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值