运算符重载实现字符串串接

来源:互联网 发布:spark sql 数据仓库 编辑:程序博客网 时间:2024/05/16 02:11
/*建立一个类 String,连接两个字符串后。具体要求:(1)私有数据成员    int Length;    //字符串的长度    char *s;       //指向字符串的指针(2)公有成员    构造函数   //缺省参数的构造函数、以对象作为参数构造函数、以一个字符串常量作为参数的构造函数    析构函数    拷贝构造函数    String operator +(String &); //重载“+”运算符    String operator =(String &); //重载“=”运算符    void show();    //输出两个字符串和结果字符*/#include<iostream>using namespace std;class String{private:    int length;    char *s;public:    String();    String(String &);    String(char *);    String operator + (String &);    String operator = (String &);    void show();    ~String();};String::String(){    length = 0;    s = new char;    s = NULL;}String::String(String &string){    s = new char;    this->length = string.length;    char *str_s = s;    while (*string.s)    {        *str_s = *string.s;        str_s++;        string.s++;    }    *str_s = '\0';}String::String(char *temp){    this->length = strlen(temp);    s = new char;    char *ptr = s;    while (*temp)    {        *ptr = *temp;        ptr++;        temp++;    }    *ptr = '\0';}String String::operator+(String &string){    char *temp_s1 = this->s;    char *temp_s2 = string.s;    while (*temp_s1)        temp_s1++;    while (*temp_s2)    {        *temp_s1 = *temp_s2;        temp_s1++;        temp_s2++;    }    *temp_s1 = '\0';    return *this;}String String::operator=(String &string){    this->length = string.length;    char *this_s = this->s, *string_s = string.s;    while (*string_s)    {        *this_s = *string_s;        this_s++;        string_s++;    }    *this_s = '\0';    return *this;}void String::show(){    cout << "长度为:" << length << endl;    cout << "字符串为:" << s;}String::~String(){    delete s;}int main(){    char a[] = "abcdefg", b[] = "ABCDEFG";    String str1(a);    String str2(str1);    String str3 = str2 + str1;    str3.show();    system("pause");    return 0;}
原创粉丝点击