//实现string类
class SwyString
{
public:
SwyString(const char* str = NULL)
{
//构造函数
if (!str)
{
length = 0;
data = new char[1];
*data = '\0';
}
else
{
length = strlen(str);
data = new char[length + 1];//strlen不计算\0
strcpy(data, str);
}
};
SwyString(const SwyString& str)
{
//拷贝构造函数 深拷贝 深复制
length = str.size();
data = new char[length + 1];
strcpy(data, str.c_str());
};
~SwyString()
{
delete []data;
length = 0;
};
SwyString operator+(const SwyString& str) const
{
//重载 + 运算符
SwyString temp;
temp.length = length + str.size();
temp.data = new char[temp.length + 1];
strcpy(temp.data, data);
strcat(temp.data, str.c_str());
return temp;
};
SwyString& operator=(const SwyString& str)
{
//重载赋值运算符
if (this == &str)
return *this;
delete[] data;
length = str.size();
data = new char[length + 1];
strcpy(data, str.c_str());
return *this;
};
SwyString operator+=(const SwyString& str)
{
//重载运算符+=
length += str.length;
char* newData = new char[length + 1];
strcpy(newData, data);
strcat(newData, str.c_str());
delete[]data;
data = newData;
return *this;
}
inline bool operator==(const SwyString& str) const
{
//重载运算符 ==
if (length != str.size())
return false;
return strcmp(data, str.c_str()) ? false : true;
};
char& operator[](int n) const
{
//重载运算符 []
if (n >= length)
return data[length - 1];
return data[n];
};
inline size_t size() const
{
return length;
};
inline const char* c_str() const
{
return data;
};
//两个友元函数 不属于此类,提供外界方便访问的接口
friend istream& operator >> (istream& is, SwyString& str)
{
//重载 >> 操作符
char temp[1000];//栈 临时空间
is >> temp;
str.length = strlen(temp);//字符串的长度 直到第一个'\0'为止
str.data = new char[str.length + 1];//堆内存,除非delete 不会回收
strcpy(str.data, temp); //也是copy到'\0'为止 就退出
return is;
};
friend ostream& operator << (ostream& os, SwyString& str)
{
//重载 << 操作符
os << str.c_str();
return os;
};
private:
char* data; //字符串
size_t length; //长度
};
SwyString s;
std::cin >> s;
std::cout << s << ":" << s.size() << std::endl;
char a[] = "hello";
char b[] = "world";
SwyString s1(a);
SwyString s2(b);
cout << s1 << "," << s2 << std::endl;
cout << s1 + s2 << std::endl;
SwyString s3 = s1 + s2;
if (s1 == s3)
std::cout << "equal\n";
else
std::cout << "not equal\n";
s1 += s2;
if (s1 == s3)
std::cout << "equal\n";
else
std::cout << "not equal\n";