首页 > 代码库 > 设计String类,并且在String类中使用运算符重载

设计String类,并且在String类中使用运算符重载

程序代码:

#include <iostream>
#include <Cstring>

using namespace std;

class String//定义String类
{
public:
    String( );//默认构造函数
    String(char *s);//构造函数
    String(String &str);//构造函数
    ~String();//析构函数
    void display( );//显示数据成员
    
    //重载>
   friend bool operator>(String &s1 , String &s2);
    
    //重载<
    friend bool operator<(String &s1 , String &s2);

    //重载==
    friend bool operator==(String &s1 , String &s2);
   
    //重载+
    friend String operator + (String &s1,String &s2 );
   
private:
    char *p;//字符指针
    int len;//字符串的长度
};

String::String()
{
    len = 0;
    p = NULL;
}

String::String(char *s)
{
    len = strlen(s);
    p = new char[len];
    strcpy(p,s);
}

String::String(String &str)
{
     len = str.len;
    p = new char[len];
    strcpy(p,str.p);
}

//析构函数
String::~String()
{
     if(!p)
    {
        delete(p);
    }
}

void String::display( )//输出p所指向的字符串
{
    cout<<p<<endl;
}

//重载>
bool operator>(String &s1 , String &s2)
{
    if(strcmp(s1.p , s2.p) > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
    
//重载<
bool operator<(String &s1 , String &s2)
{
    if(strcmp(s1.p , s2.p) < 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

//重载==
bool operator==(String &s1 , String &s2)
{
    if(0 == strcmp(s1.p , s2.p))
    {
        return true;
    }
    else
    {
        return false;
    }
}


//重载+
String operator + (String &s1 , String &s2 )
{
    String s;
    s.len = s1.len+s2.len;
    s.p = new char(s.len+1);
    strcpy(s.p,s1.p);
    strcat(s.p,s2.p);
    return s;
}


void main( )
{
    String s1("Hello ");
    String s2("World");
    String s3;

    bool flag;

    cout<<"s1 = ";
    s1.display();

    cout<<"s2 = ";
    s2.display();

    //判断s1是否大于s2
    flag = s1 > s2;
    cout<<"s1 > s2 = "<<flag<<endl;

    //判断s1是否小于s2
    flag = s1 < s2;
    cout<<"s1 < s2 = "<<flag<<endl;

     //判断s1是否等于s2
    flag = s1 > s2;
    cout<<"s1 == s2 = "<<flag<<endl;

    //计算s1+s2
    s3 = s1 + s2;
    cout<<"s1 + s2 = ";
    s3.display();
    
  system("pause");
}


执行结果: