class my_string {
friend std::ostream& operator<<(ostream& os, const my_string& str);
friend std::istream& operator >>(istream& is, my_string& str);
public:
my_string(const char * str = NULL);
my_string(const my_string &);
~my_string();
my_string operator=(const my_string &);
my_string operator+(const my_string &);
bool operator==(const my_string&);
char& operator[](int);
int size() { return strlen(this->data) + 1; }
private:
char* data;
};
my_string::my_string(const char* str)
{
if (str == NULL)this->data = NULL;
else
{
this->data = new char[strlen(str) + 1];
strcpy(data,str);
}
}
my_string::my_string(const my_string& other)
{
if (other.data == NULL)this->data = NULL;
else
{
this->data = new char[strlen(other.data)+1];
strcpy(this->data,other.data);
}
}
my_string::~my_string()
{
delete[] this->data;
}
my_string my_string::operator=(const my_string& other)
{
delete[] this->data;
if (other.data == NULL)this->data = NULL;
else
{
this->data = new char[strlen(other.data)+1];
strcpy(this->data,other.data);
}
return *this;
}
my_string my_string::operator+(const my_string& other)
{
if (other.data == NULL)return *this;
else if(this->data == NULL)
{
this->data = new char[strlen(other.data) + 1];
strcpy(this->data, other.data);
return *this;
}
else
{
my_string strTmp;
strTmp.data = new char[strlen(this->data) + strlen(other.data) + 1];
strcpy(strTmp.data, this->data);
strcat(strTmp.data, other.data);
return strTmp;
}
}
bool my_string::operator==(const my_string& other)
{
int tmp = 0;
tmp = strcmp(this->data,other.data);
if (tmp == 0)return 1;
else return 0;
}
char& my_string::operator[](int index)
{
return this->data[index];
}
ostream& operator<<(ostream& os, const my_string& str)
{
os << str.data;
return os;
}
istream& operator>>(istream& is, my_string& str)
{
char buffer[4096];
is >> buffer;
str.data = buffer;
return is;
}
int main()
{
my_vector<int> mv1(3);
mv1[0] = 0;
mv1[1] = 1;
mv1[2] = 2;
my_vector<int> mv2(mv1);
cout << mv2[0] << mv2[1] << mv2[2] << endl;
my_string str1, str2,str3;
str1 = "qweewq";
str2 = "qweewq";
str3 = str1 + str2;
cout << str3 << endl;
if (str1 == str2)cout << "str1 和 str2 相同 " << endl;
cout << str1[1] << str1.size() << endl;
return 0;
}