C++簡易Stringクラス
1674 ワード
以下はC++実装の簡易Stringクラスで、関数宣言のパラメータタイプ(特に参照とconstキーワードの使用に注意してください!)に注意してください.
#include
#include
#include
#include
#include
#include
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<