建立一个字符串类名为String,至少写出三个构造函数
,重载赋值等号=、加号+、关系等于==、>、>=、<、<=,
另写出析构函数和其他的成员函数,如求字符串的长度、输出字符串等。在main()中定义String类对象测试所写函数是否正确。
#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(const Str &s){
length = s.length;
str = (char*)malloc((length + 1)*sizeof(char));
strcpy(str, s.str);
}
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 = ss;
return *this;
}
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;
}
int operator<=(const Str &s){
if(strcmp(s.str, str) >= 0 )
return 1;
else
return 0;
}
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):\t" << str << endl;
cout << "(str2):\t" << str2 << endl;
cout << "(str < str2):\t" << (str<=str2) <<endl;
cout << "sum(str + str2):\t" << str+str2 << endl;
cout << "(str):\t" << str << endl;
cout << "(str2):\t" << str2 << endl;
str += str2;
cout << "excute (str += str2) str = \t" << str << endl;
cout << "(str2):\t" << str2 << endl;
str = str2;
cout << "excute (str = str2) str = \t" << str << endl;
cout << "(str2):\t" << str2 << endl;
Str str4 = str2;
cout << "excute (str4 = str2) str2 = \t" << str2 << endl;
cout << "(str4):\t" << str4 << endl;
cout << "(str4 < str2):\t" << (str4<=str2) <<endl;
return 0;
}