您的位置:首页 > 编程语言 > C语言/C++

C++ 写自己的string类(作风::懒)

2016-02-26 23:22 323 查看
#include <iostream>
#include<cstdlib>
#include <conio.h>
using namespace std;

class Cstring
{
private:
unsigned int len;
char *st;
explicit Cstring(const unsigned int i)
{
len = 0;
st = new char[i+1];
return;
}
public:
~Cstring()
{
delete []st;
st = 0;
}
explicit	Cstring()
{
len = 0;
st = new char[len+1];
st[0] = '\0';
}
Cstring(const Cstring &s)
{
len = s.len;
st = new char[len + 1];
for ( int i = 0; i < len; i++)
{
st[i] = s[i];
}
st[len] = '\0';
return;
}
explicit Cstring(const char *const ch)
{
len = strlen(ch);
st = new char[len + 1];
for ( int i = 0; i < len; i++)
{
st[i] = ch[i];
}
st[len] = '\0';
return;
}
explicit	Cstring(const char ch)
{
len = 1;
st = new char[len + 1];
st[0] = ch;
st[1] = '\0';
return;
}
char &operator[](unsigned int i)const
{
if (i > len - 1)
{
return st[len - 1];
}
else
return st[i];
}
char &operator[](unsigned int i)
{
if (i > len - 1)
{
return st[len - 1];
}
else
return st[i];
}
Cstring &operator=(const char * const ch)
{
if (strcmp(st, ch) == 0)
return *this;
char *p = st;
delete []p;
p = 0;
len = strlen(ch);
st = new char[len + 1];
for (unsigned int i = 0; i < len; i++)
{
st[i] = ch[i];
}
st[len] = '\0';
return *this;
}
Cstring &operator=(const Cstring &s)
{
if (this == &s)
return *this;
char *p = st;
delete[]p;
p = 0;
len = s.len;
st = new char[len + 1];
for ( int i = 0; i < len; i++)
{
st[i] = s[i];
}
st[len] = '\0';
return *this;
}
const	Cstring operator+(const Cstring &s)
{
unsigned int temlen = len + s.len;
Cstring temp(temlen);
for (unsigned int i = 0; i < len; i++)
{
temp.st[i] = st[i];
}
for (unsigned int j = 0; j < s.len; j++)
{
temp.st[len + j] = s.st[j];
}
temp.len = temlen;
temp.st[temp.len] = '\0';
return temp;
}
const	Cstring operator+(const char *const ch)
{
unsigned int templen = len + strlen(ch);
Cstring temp(templen);
for (unsigned int i = 0; i < len; i++)
{
temp.st[i] = st[i];
}
for (unsigned int j = 0; j < strlen(ch); j++)
{
temp.st[len + j] = ch[j];
}
temp.len = templen;
temp.st[temp.len] = '\0';
return temp;
}

friend ostream&operator<<(ostream &o, const Cstring &s)
{
o << s.st;
return o;
}
friend istream&operator>>(istream &in,  Cstring &s)
{
char ch;
int i = 0;
while ((ch = cin.get())!='\n')
{
if (!i)
{
delete[]s.st;
s.st = 0;
s.len = i+1;
s.st = (char*)realloc(s.st, (s.len+1)*sizeof(char));
s.st[i] = ch;
s.st[i+1] = '\0';
i++;
}
else
{
s.len = i + 1;
s.st = (char*)realloc(s.st, (s.len + 1)*sizeof(char));
s.st[i] = ch;
s.st[i + 1] = '\0';
i++;
}
}
return in;
}

};

int main()
{
Cstring s;
s = "123333333";
s[4] = '1';
Cstring ss(s);
cout << ss << endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: