重载C++运算符
题目
实现一个通过重载以下运算符来执行字符串操作的类:<<、>>、= 和 ==。例如,考虑以下代码:
StrShift example;
example = “hello world!”;
printf(“\”example << 2\” 的结果为 %s\n“, example << 2); 在上述代码中,输出将是“llo world!he”,这显示了字符串“hello world!”的最后两个字符向左旋转到了字符串的前面。请注意,状态是保持的,因此两次调用 example << 1 将得到与一次调用 example << 2 相同的结果。
解题方案:
#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
String();
String(int len);
String(const char* str);
String(const String &other);
String& operator=(const String& other);
bool operator==(String& other);
char* operator<<(int n);
char* operator>>(int n);
~String();
private:
int length;
char* str;
};
String::String()
{
this->length = 0;
this->str = NULL;
}
String::String(int len)
{
this->length = len;
this->str = new char[len];
memset(this->str, 0, len);
}
String::String(const char* str)
{
if (str == NULL)
{
this->length = 0;
this->str = new char[1];
strcpy(this->str, "");
return;
}
this->length = strlen(str);
this->str = new char[this->length + 1];
strcpy(this->str, str);
}
String::String(const String & other)
{
this->length = other.length;
this->str = new char[this->length+1];
strcpy(this->str, other.str);
}
String & String::operator=(const String & other)
{
if (this == &other)
{
return *this;
}
if (this->str != NULL)
{
delete[] this->str;
this->str = NULL;
this->length = 0;
}
this->length = other.length;
this->str = new char[this->length + 1];
strcpy(this->str, other.str);
return *this;
}
bool String::operator==(String & other)
{
if (this == &other)
{
return true;
}
if (this->length != other.length)
{
return false;
}
if (strcmp(this->str, other.str) != 0)
{
return false;
}
return true;
}
char* String::operator<<(int n)
{
if(this->str != NULL)
{
String str = *this;
for(int i = 0; i < this->length; i++)
{
this->str[i] = str.str[(this->length - n + i)%(this->length)];
}
return this->str;
}
return NULL;
}
char* String::operator>>(int n)
{
if(this->str != NULL)
{
String str = *this;
for(int i = 0; i < this->length; i++)
{
this->str[i] = str.str[(n + i)%(this->length)];
}
return this->str;
}
return NULL;
}
String::~String()
{
if (this->str != NULL)
{
delete[] this->str;
this->str = NULL;
this->length = 0;
}
}
int main(int argc, char *argv[])
{
String example("hello world!");
String str1 = example;
printf (" \" example << 2\" result in %s\n ", (example >> 2));
printf (" \" example >> 2\" result in %s %s\n ", (example << 1),(example << 1));
return 0;
}