string类运算符重载

#include<iostream>
#include<string.h>
using namespace std;
class String 
{
private:
 char*ps;
public:
 String(char*p = " "):ps(new char[strlen(p)+1])
 {
  strcpy(ps, p);
 }
 ~String()
 {
  delete[] ps;
  ps = NULL;
 }
 String(const String&ref):ps(new char[strlen(ref.ps)+1])
 {
  strcpy(ps, ref.ps);
 }
 String &operator=(const String&ref)
 {
  if (this->ps != NULL)
  {
   delete[]ps;
   ps = NULL;
  }
  this->ps = new char[strlen(ref.ps) + 1];
  strcpy(this->ps, ref.ps);
  return *this;
 }
 String &operator+=(const String&ref)
 {
  String a;
  a.ps = new char[strlen(this->ps) + strlen(ref.ps) + 1];
  strcpy(a.ps, this->ps);
  strcat(a.ps, ref.ps);
  this->ps = new char[strlen(a.ps) + 1];
  strcpy(this->ps, a.ps);
  return *this;
 }
 String operator+(const String&ref)const
 {
  String a;
  a.ps= a.ps = new char[strlen(this->ps) + strlen(ref.ps) + 1];
  strcpy(a.ps, this->ps);
  strcat(a.ps, ref.ps);
  return a;
 }
 bool operator==(const String&ref)const
 {
  if (strcmp(this->ps, ref.ps) == 0)
   return true;
  else
   return false;
 }
 bool operator!=(const String&ref)const
 {
  if (strcmp(this->ps, ref.ps) == 0)
   return false;
  else
   return true;
 }
 bool operator<(const String&ref)const
 {
  if (strcmp(this->ps, ref.ps) < 0)
   return true;
  else
   return false;
 }
 bool operator>(const String&ref)const
 {
  if (strcmp(this->ps, ref.ps) >0)
   return true;
  else
   return false;
 }
 bool operator<=(const String&ref)const
 {
  if (strcmp(this->ps, ref.ps) <= 0)
   return true;
  else
   return false;
 }
 bool operator>=(const String&ref)const
 {
  if (strcmp(this->ps, ref.ps) >=0)
   return true;
  else
   return false;
 }
 char operator[](const int i)const
 {
  return this->ps[i];
 }
 void show()
 {
  cout << ps << endl;
 }
};
int main(){String s1("aaa");
 String s2("bbb");
 String s3("ccc");
 String s4("ddd");
 String s5;
    s5 = s1 + s2 + s3 + s4;
 s5.show();
 s5 += s4;
 s5.show();
 s5 = s1;
 s5.show();
 if (s4 == s1)
 {
  cout << 1 <<endl;
 }
 else
 {
  cout << 0 << endl;
 }
 if (s4 != s1)
 {
  cout << 1 << endl;
 }
 else
 {
  cout << 0 << endl;
 }
 cout << s4[2] << endl;
 return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值