运算符重载

#include 
#include
using namespace std;
//定义mystring类
class mystring
{
private :
    char *str;//记录c风格字符串
    int size;//记录字符串长度
public :
    //无参构造
    mystring():size(10)
    {
        str=new char[size];//构造一个长度为10的字符串
        strcpy(str,"");
    }
    //有参构造
    mystring(const char *s)
    {
        size=strlen(s);
        str=new char [size+1];
        strcpy(str,s);

    }
    //拷贝构造
    mystring(mystring & other):str(new char(*(other.str))),size(other.size)//new char [other.size]
    {
        strcpy(str,other.str);
        cout<<"构造拷贝"<=size)
        {
            cout<<"输入不合法"<size-1;
        temp.str=new char[this->size+other.size-1];//两个字符串结尾\0
        strcpy(temp.str,this->str);
        strcat(temp.str,other.str);
        return temp;
    }
    //= 运算符重载
    mystring & operator = (const mystring  & other)
    {
        if(this!=&other)
        {
            delete  this->str;
            this->str=new char[other.size];
            strcpy(this->str,other.str);

        }
         return *this;
    }
    //[]运算符重载
     char operator [](int pos)
     {
         if(pos>size||pos<0)
         {
             cout<<"输入不合法"<str,other.str))
            return true;
        else
            return false;
     }
      //>运算符重载
      bool operator >(const mystring & other)const
      {
          if(stricmp(this->str,other.str)>0)
          {
              return true;
          }
          else
              return false;
      }
      //<运算符重载
      bool operator <(const mystring & other)const
      {
          if(stricmp(this->str,other.str)<0)
          {
              return true;
          }
          else
              return false;
      }
      friend ostream &operator <<(ostream &cout,const mystring &other);
       friend istream &operator >>(istream &cin, mystring &other);


};
//输出运算符<<
ostream &operator <<(ostream &cout,const mystring &other)
{
    cout<>
istream &operator >>(istream &cin, mystring &other)
{
    string str;
    cout<<"请输入一个字符串"<>str;
    delete other.str;
    memset(other.str,0,other.size);
    strcpy(other.str,str.c_str());
    other.size=str.size();
    return cin;
}


int main()
{
    //有参构造
    mystring str("666888 ni hao");
    cout<<"有参构造:"<运算符重载
     cout<<">运算符重载"<<(str>str1)<>
     cin>>str1;
     cout<<"输入运算符"<

输出结果为:

运算符重载_第1张图片

 

你可能感兴趣的:(c++,算法)