实现了输入输出流的重载,能够输出字符串长度,重载了+、+=、=等运算符。
String类代码:
#include
#include
using namespace std;
class String
{
private:
char *str;
int maxsize;
public:
String(int x = 100)
{
maxsize = x;
str = new char[x];
}
String(const String &x)
{
maxsize = x.maxsize;
str = new char[maxsize];
strcpy(str, x.str);
}
String &operator=(const String &x)
{
delete[] str;
maxsize = x.maxsize;
str = new char[maxsize];
strcpy(str, x.str);
return *this;
}
int stringLength()
{
return strlen(str);
}
friend ostream &operator<<(ostream &os, String &x)
{
os << x.str; return os;
}
friend istream &operator>>;(istream &is, String &x)
{
is >> x.str;
return is;
}
friend String operator+(String a, String b)
{
String c(1000);
strcpy(c.str, a.str);
strcat(c.str, b.str);
return c;
}
friend String &operator+=(String &a, String &b)
{
strcat(a.str, b.str);
return a;
}
char operator[](int x)
{
try
{
if (x >= maxsize)
throw "String Overflow.";
else
return str[x];
}
catch (const char *s)
{
cout << s << endl;
}
}
};