c++ 模仿string类
#include <iostream>
#include <cstring>
using namespace std;
class myString{
private:
char *str;
int size;
public:
myString():size(10)
{
str = new char[size];
cout << "无参构造" << endl;
}
myString(const char *s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
cout << "有参构造" << endl;
}
myString(const myString & other)
{
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
cout << "拷贝构造" << endl;
}
~myString()
{
delete []str;
cout << "析构函数" << endl;
}
bool empty()
{
if(strlen(str) == 0)
{
return true;
}
else
{
return false;
}
}
int length()
{
return size;
}
const char * c_str()
{
return str;
}
char &at(int pos)
{
if(pos >= size || pos < 0)
{
cout << "段错误" << endl;
}
return str[pos];
}
myString &operator= (const myString &other)
{
if(this == &other)
{
return *this;
}
delete []str;
size = other.size;
str = new char[size+1];
strcpy(str, other.str);
return *this;
cout << "拷贝赋值" << endl;
}
char &operator[] (int pos)
{
if(pos >= size || pos < 0)
{
cout << "段错误" << endl;
}
return str[pos];
}
myString operator+ (const myString &other)
{
myString temp;
delete []temp.str;
temp.size = size + other.size;
temp.str = new char[temp.size + 1];
strcat(temp.str, str);
strcat(temp.str, other.str);
return temp;
}
bool operator== (const myString &other)
{
return str == other.str;
}
friend ostream &operator<< (ostream& L, const myString &R);
friend istream &operator>> (istream &L, myString &R);
};
ostream &operator<< (ostream& L, const myString &R)
{
L << R.str;
return L;
}
istream &operator>> (istream &L, myString &R)
{
if(R.str != NULL)
{
delete []R.str;
R.str = nullptr;
}
delete [] R.str;
char temp[20];
L >> temp;
R.str = new char(strlen(temp) + 1);
strcpy(R.str, temp);
return L;
}
int main()
{
myString s1("word");
cout << "s1 = " << s1.c_str() << endl;
myString s2(s1);
cout << "s2 = " << s2.c_str() << endl;
myString s3;
if(!s3.empty())
{
s3 = s2;
}
cout << "s3.length() = " << s3.length() << endl;
cout << "s3.c_str() = " << s3.c_str() << endl;
cout << "s3.at(3) = " << s3.at(3) << endl;
myString s4("hello");
cout << "s4[1] = " << s4[1] << endl;
myString s5;
s5 = s4 + s1;
cout << "s5 = " << s5.c_str() << endl;
cout << s4;
cin >> s5;
cout << s5;
return 0;
}