C++练习 | 运算符重载练习(字符串相关)

#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <iomanip>
using namespace std;
class String
{
private:
    char *s;
public:
    String()
    {
        s=new char[1000];
    }
    String(const char *t)
    {
        s=new char[1000];
        strcpy(s,t);
    }
    String(const String &t)
    {
        s=new char[1000];
        strcpy(s,t.s);
    }
    ~String()
    {
        delete []s;
    }
    String & operator=(const char *t)
    {
        strcpy(this->s,t);
        return *this;
    }
    String & operator=(const String &t)
    {
        this->s=t.s;
        return *this;
    }
    String operator+(const char *t)
    {
        char *t1=nullptr;
        strcpy(t1,this->s);
        strcat(t1,t);
        return t1;
    }
    String operator+(const String &t)
    {
        char *t1 = nullptr;
        strcpy(t1,this->s);
        strcat(t1,t.s);
        return t1;
    }
    String & operator+=(const char *t)
    {
        strcat(this->s,t);
        return *this;
    }
    String & operator+=(const String &t)
    {
        strcat(this->s,t.s);
        return *this;
    }
    friend istream & operator>>(istream & is, String &t1)
    {
        is>>t1.s;
        return is;
    }
    friend ostream & operator<<(ostream & os, String &t2)
    {
        os<<t2.s;
        return os;
    }
    friend bool operator==(const String &t1, const char *t2)
    {
        if(strcmp(t1.s,t2))
            return 0;
        else
            return 1;
    }
    friend bool operator==(const String &t1, const String &t2)
    {
        if(strcmp(t1.s,t2.s))
            return 0;
        else
            return 1;
    }
    friend bool operator!=(const String &t1, const char *t2)
    {
        return strcmp(t1.s,t2);
    }
    friend bool operator!=(const String &t1, const String &t2)
    {
        return strcmp(t1.s,t2.s);
    }
};
int main()
{
    String s;
    s += "hello";
    cout<<s<<endl;
    String s1("String1");
    String s2("copy of ");
    s2 += "String1";
    cout << s1 << "\n" << s2 << endl;
    String s3;
    cin >> s3;
    cout << s3 << endl;
    String s4("String4"), s5(s4);
    cout << (s5 == s4) << endl;
    cout << (s5 != s4) << endl;
    String s6("End of "), s7("my string.");
    s6 += s7;
    cout << s6 << endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/tsj816523/p/10705924.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值