7——19homework

文章展示了如何在C++中创建一个名为MyString的类,该类实现了字符串的基本功能,包括无参构造、有参构造、拷贝构造、拷贝赋值以及一些成员函数如isempty、getsize、c_str等。此外,还覆盖了+和>运算符以支持字符串拼接和比较操作。
摘要由CSDN通过智能技术生成

代码:

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

class MyString
{
private:
    char *str;
    int size;
public:
    MyString():size(10)    //无参构造函数
    {
        str=new char[size];
        strcpy(str,"");
    }
    MyString(const char *s)  //有参构造函数
    {
        size=strlen(s);
        str=new char[size+1];
        strcpy(str,s);
    }
    MyString(const MyString& other):size(other.size)    //拷贝构造函数
    {
        str=new char[size+1];
        strcpy(str,other.str);
        cout<<"拷贝构造"<<endl;
    }
    MyString& operator=(const MyString &other)      //拷贝赋值函数
    {
        this->str=new char[size+1];
        this->size=other.size;
        strcpy(str,other.str);

        return *this;

    }
    bool isempty()      //判空函数
    {
        if(size==0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    int getsize()    //得到字符串长度
    {
        return  size;
    }
    char *c_str()     //得到字符串
    {
        return str;
    }
    char &at(int pos)    //输出具体位置的字符
    {
        return str[pos-1];
    }
    const MyString operator+ (const MyString &R)const   //运算符+重构
    {
        MyString temp;
        temp.str=strcat(this->str,R.str);
        temp.size=this->size+R.size;

        return temp;
    }
   MyString & operator+=(const MyString &R)   //运算符+=重构
   {
       this->size=this->size+R.size;
       this->str=strcat(this->str,R.str);
       return *this;
   }
   bool operator>(const MyString &R)const  //运算符>重构
   {
       if(strcmp(this->str,R.str))
           return true;
       else
           return false;

   }

    ~MyString(){}
};

int main()
{
    MyString m1("hello");
    MyString m2;
    m2=m1;
    cout<<m2.c_str()<<endl;
    m1+=m2;
    cout<<m1.c_str()<<endl;
    MyString m3;
    m3=m1+m2;
    cout<<m3.c_str()<<endl;
    if(m1>m2)
    {
        cout<<"m1>m2"<<endl;

    }
    cout<<m1.at(8)<<endl;
    cout << "Hello World!" << endl;
    return 0;
}

思维导图

在这里插入图片描述

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值