---
title: "简单字符串类实现"
author: "bliuqing"
date: "2012-02-28T22:03:19Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-02-28T22:03:19Z"
id: 1430904
url: "https://bliuqing.iteye.com/blog/1430904"
---

[转 http://www.dogame.com.cn/gamerc/jc\_show.php?id=6051】

main函数：  
#include &lt;iostream&gt;  
#include "strings.h"  
using namespace std;  
int main(){  
Strings s3;  
Strings s4;  
Strings s5;  
s3.display();  
Strings s1("hello");  
s1.display();  
Strings s2(s1);  
s2.display();  
s3 = s2;  
s3.display();  
s4 = s1+s2;  
s4.display();  
s5 = s4 + "good";  
s5.display();  
return 0;  
}

strings.h函数  
#ifndef \_STRINGS_  
#define \_STRINGS_  
#include&lt;iostream&gt;  
using namespace std;  
class Strings{  
public:  
Strings();  
Strings(char \*s);  
Strings(const Strings &s);  
Strings& operator = (const Strings& s);  
Strings& operator + (const Strings& s);  
Strings& operator + (const char \*s);  
~Strings(){  
if(str != NULL)  
delete \[] str;  
cout&lt;&lt;"~Strings() is called"&lt;&lt;endl;  
}  
display();  
private:  
char \*str;  
};  
#endif

strings.cpp函数  
#include "strings.h"  
#include &lt;iostream&gt;  
using namespace std;  
Strings::Strings(){ // 默认构造函数  
str = new char('A'); //初试化为字符A  
//str = "nothing"; 试试如此初试话 :-) 呵呵  
cout&lt;&lt;"Strings is called"&lt;&lt;endl;  
}  
Strings::Strings(char \*s){  
str = new char\[strlen(s) + 1]; // 带一个参数的构造函数  
if(str)  
strcpy(str, s);  
cout&lt;&lt;"Strings(char \*s) is called"&lt;&lt;endl;  
}  
Strings::Strings(const Strings &s){ // copy构造函数  
str = new char\[strlen(s.str) + 1];  
if(str)  
strcpy(str, s.str);  
cout&lt;&lt;"Strings(const Strings &s) is called "&lt;&lt;endl;  
}  
Strings& Strings::operator = (const Strings &s){ // 赋值运算  
if(this != &s){ // 如果str不是它本身  
if(str != NULL)  
delete \[] str; //防止内存泄露  
str = new char\[strlen(s.str) + 1];  
strcpy(str, s.str);  
cout&lt;&lt;"Strings(const Strings &s) is called "&lt;&lt;endl;  
}  
return \*this;  
}  
Strings& Strings::operator + (const Strings& s){ // 加法运算  
char * temp;  
 temp = new char\[strlen(str)+strlen(s.str)+1]; //需要重新申请内存，原来的内存不够  
strcpy(temp, str);  
delete \[] str;  
strcat(temp,s.str);  
str = temp;  
return \*this;  
}  
Strings& Strings::operator + (const char \*s){ // 加法运算  
char * temp;  
temp = new char\[strlen(str)+strlen(s)+1];  
strcpy(temp, str);  
delete \[] str;  
strcat(temp,s);  
str = temp;  
return \*this;  
}  
Strings::display(){ // 显示函数  
char \*p=str;  
while(\*p != '\\0'){  
cout&lt;&lt;\*p;  
p ++;  
}  
cout&lt;&lt;endl;  
cout&lt;&lt;"display is called "&lt;&lt;endl;  
}