以下是C++实现的简易String类,需要注意和小心函数声明里面的参数类型(特别是引用和const关键字的使用!)
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
using namespace std;
class Str{
private:
char *str;
char length;
public:
Str():str(NULL), length(0){}
Str(char *s, int l){
str = (char*)malloc((l+1)*sizeof(char));
strcpy(str, s);
length = l;
}
int size(){ return length; }
Str operator+(const Str &s){
char *ss = (char*)malloc((s.length + length+1)*sizeof(char));
//length = s.length + length;
strcpy(ss, str);
strcat(ss, s.str);
//free(str);
return Str(ss, s.length + length);
}
Str(const Str &s){
length = s.length;
str = (char*)malloc((length + 1)*sizeof(char));
strcpy(str, s.str);
}
Str& operator+=(const Str &s){
char *ss = (char*)malloc((s.length + length + 1)*sizeof(char));
length = s.length + length;
strcpy(ss, str);
free(str);
strcat(ss, s.str);
str = ss;
return *this;
}
Str& operator=(const Str &s){
if (this == &s) return *this;
length = s.length;
char *ss = (char*)malloc((length + 1)*sizeof(char));
free(str);
strcpy(ss, s.str);
str = ss;
return *this;
}
bool operator==(const Str &s){
if (s.length != length) return false;
else return strcmp(s.str, str) == 0;
}
friend ostream &operator<<(ostream &out, Str &ss){
out << ss.str;
return out;
}
~Str()
{
free(str);
}
};
int main()
{
char s[100], s2[100];
strcpy(s, "this is my string");
strcpy(s2, "this is my house");
Str str(s, strlen(s));
Str str2(s2, strlen(s2));
cout << str << endl;
cout << str2 << endl;
cout << str + str2 << endl;
cout << str << endl;
cout << str2 << endl;
str += str2;
cout << str << endl;
cout << str2 << endl;
str = str2;
cout << str << endl;
cout << str2 << endl;
Str str4 = str2;
cout << str2 << endl;
cout << str4 << endl;
return 0;
}