作者:永欣慧娟766 | 来源:互联网 | 2023-01-30 18:57
#include
#include
using namespace std;
class String
{
public:
String()
:_data(new char[1])
{
*_data = '\0';
cout <<"String()" <}
String(const char* str) //构造
{
int len = strlen(str);
_data = new char[len + 1];
strcpy(_data, str);
cout <<"String(const char* str)" <}
//s2(s1)
String(const String& other) //拷贝构造
{
int len = strlen(other._data);
_data = new char[len + 1];
strcpy(_data, other._data);
cout <<"String(const String& other)" <}
//s2=s1
String& operator=(const String& other) //赋值运算符的重载
{
if (this != &other) //不是自己给自己赋值
{
delete[] _data; //释放s2原有的空间
int len = strlen(other._data);
_data = new char[len + 1];
strcpy(_data, other._data);
}
cout <<"String& operator=(const String& other)" <return *this;
}
~String()
{
delete[] _data;
cout <<"~String()" <}
size_t Size() const
{
return strlen(_data);
}
bool operator <(const String& other)
{
char* str1 = other._data;
char* str2 = _data; //this指针所指向的
while (*str1 && *str2) //当两个内容均不为空时
{
if (*str1 <*str2)
{
return true;
}
else if (*str1 > *str2)
{
return false;
}
else
{
str1++;
str2++;
}
}
//此时至少有一个走到结尾
if (*str1 != NULL && *str2 == NULL)
{
return false;
}
else if (*str2 != NULL && *str1 == NULL)
{
return true;
}
else
{
return false;
}
}
bool operator > (const String& other) //重载 >
{
char* str1 = other._data;
char* str2 = _data; //this指针所指向的
while (*str1 && *str2) //当两个内容均不为空时
{
if (*str1 > *str2)
{
return true;
}
else if (*str1 <*str2)
{
return false;
}
else
{
str1++;
str2++;
}
}
//此时至少有一个走到结尾
if (*str1 != NULL && *str2 == NULL)
{
return true;
}
else if (*str2 != NULL && *str1 == NULL)
{
return false;
}
else
{
return false;
}
}
bool operator>=(const String& other)
{
if (*this {
return false;
}
else
{
return true;
}
}
bool operator<=(const String& other)
{
if (*this > other)
{
return false;
}
else
{
return true;
}
}
bool operator==(const String& other)
{
if (strlen(_data) == strlen(other._data))
{
for (size_t i = 0; i {
if (_data[i] != other._data[i])
{
return false;
}
else
{
return true;
}
}
}
return false;
}
char& operator[](size_t pos)
{
return _data[pos]; //返回该位置处的字符
}
protected:
char* _data;
};
#include "String.h"
void test()
{
//String p1;
//String p2;
//String p2(p1);
//p1 = p2;
String s1("1234");
String s3("34567");
String s2(s1);
//cout <//cout <//cout <//cout <
cout <}
int main()
{
test();
return 0;
}