10月8日作业(C++)

题目:

 

代码:

#include<iostream>
#include<string>
#include<cstring>

using namespace std;

class my_string
{
private:
    char *s;
public:
    //构造函数
    my_string(){}
    my_string(char *str){
        s=new char[strlen(str)];
        strcpy(s,str);
    }
    //析构函数
    ~my_string(){
        delete s;
    }
    //运算符重载函数
    //+=运算符
    my_string  &operator+=(const my_string &R){
        char *temp=new char(strlen(this->s));
        strcpy(temp,this->s);
        delete this->s;
        this->s=new char[strlen(this->s)+strlen(R.s)];
        strcpy(this->s,temp);
        strcat(this->s,R.s);
        delete temp;
        return *this;
    }
    //+运算符
    const my_string  operator+(const my_string &R)const{
        my_string temp;
        temp.s=new char[strlen(this->s)+strlen(R.s)];
        strcpy(temp.s,this->s);
        strcat(temp.s,R.s);
        return temp;
    }
    //>
    bool operator>(my_string &R)const{
        return strcmp(this->s,R.s)>0?true:false;
    }
    //<
    bool operator<(my_string &R)const{
        return strcmp(this->s,R.s)<0?true:false;
    }
    //==
    bool operator==(my_string &R)const{
        return !strcmp(this->s,R.s);
    }
    //[]
    char &operator[](int index){
        return this->s[index];
    }
    //成员函数
    char *getStr(){
        return s;
    }
};

int main(int argc, const char *argv[])
{
    my_string s1("hello");
    cout<<s1.getStr()<<endl;
    my_string s2=" world";
    cout<<s2.getStr()<<endl;
    s1+=s2;
    cout<<s1.getStr()<<endl;
    my_string s3;
    s3=s1+s2;
    cout<<s3.getStr()<<endl;
    cout<<(s1>s2)<<endl;
    cout<<(s1<s2)<<endl;
    cout<<(s1==s2)<<endl;
    cout<<s1[1]<<endl;
    s1[4]='a';
    cout<<s1[4]<<endl;
    cout<<s1.getStr()<<endl;
    return 0;
}

效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值