代码
#include <iostream>
#include <string>
#include <vld.h>
using namespace std;
class String
{
public:
String(char *ptr = NULL)
{
if (ptr != NULL)
{
mpstr = new char[strlen(ptr) + 1 + 4];
strcpy(mpstr + 4, ptr);
}
else
{
mpstr = new char[1 + 4];
mpstr[4] = '\0';
}
*((int*)mpstr) = 1;
}
String(const String &str)
{
mpstr = str.mpstr;
++(*(int *)mpstr);
}
String&operator=(const String &src)
{
if (this == &src)
{
return *this;
}
(*(int *)mpstr)--;
if (*((int *)mpstr) == 0)
{
delete[]mpstr;
mpstr = NULL;
}
mpstr = src.mpstr;
++(*((int *)mpstr));
return *this;
}
~String()
{
(*((int *)mpstr))--;
if (*((int *)mpstr) == 0)
{
delete[]mpstr;
mpstr = NULL;
}
}
bool operator>(const String &src)
{
return strcmp(mpstr, src.mpstr) > 0;
}
bool operator<(const String &src)
{
return strcmp(mpstr, src.mpstr) < 0;
}
bool operator==(const String &src)
{
return strcmp(mpstr, src.mpstr) == 0;
}
int length()const { return strlen(mpstr+4); }
char& operator[](int index)
{
char *tmp = new char[strlen(mpstr + 4) + 1 + 4];
strcpy(tmp + 4, mpstr + 4);
*((int*)tmp) = 1;
--(*((int*)mpstr));
mpstr = tmp;
return (mpstr + 4)[index];
}
private:
char *mpstr;
friend ostream& operator<<(ostream &out, const String &src);
friend String operator+(const String &lhs, const String &rhs);
};
String operator+(const String &lhs, const String &rhs)
{
int n = lhs.length() + rhs.length() + 1;
cout << "lhs.mpstr为:" << lhs.mpstr+4 << endl;
cout << "rhs.mpstr为:" << rhs.mpstr+4 << endl;
char *ptmp = new char[n];
cout << "lhs.length()的大小为:" << lhs.length() << endl;
cout << "rhs.length()的大小为:" << rhs.length() << endl;
cout << "ptmp数组开辟的大小为:" << n<<endl;
char *q = "wangpeng";
cout << "q的大小为:" << strlen(q) << endl;
cout << "q为:" << q << endl;
char *lhsT = (char *)(((int *)lhs.mpstr)+1);
char *rhsT = (char *)(((int *)rhs.mpstr) + 1);
strcpy(ptmp, lhsT);
strcat(ptmp, rhsT);
String tmp(ptmp);
delete []ptmp;
return tmp;
}
ostream& operator<<(ostream &out, const String &src)
{
out << src.mpstr + 4;
return out;
}
int main()
{
String str1("wangpeng") ;
String str2("hello");
String str3 = str1 + str2;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
return 0;
}