今天写了一个类string来模拟实现string,其中进行了常用的运算符重载。分别对+,=,==,<,>,[]进行了重载
#pragma once
#include <string>
class Cstring
{
public:
//默认构造函数
Cstring() { this->m_s = new char('\0'); }
Cstring(char* s) :m_s(s){}
Cstring(const char* s){
m_s = new char[strlen(s) + 1];
strcpy(m_s, s);
}
//拷贝构造函数
Cstring(const Cstring& ch)
{
m_s = new char[strlen(ch.m_s) + 1];
strcpy(m_s, ch.m_s);
}
Cstring& operator=(const Cstring& s)
{
this->m_s = new char[strlen(s.m_s) + 1];
strcpy(this->m_s, s.m_s);
return *this;
}
Cstring operator+(const Cstring& s)
{
Cstring temp;
temp.m_s = new char[strlen(this->m_s) + strlen(s.m_s) + 1];
strcpy(temp.m_s, this->m_s);
strcat(temp.m_s, s.m_s);
return temp;
}
bool operator==(const Cstring& st)
{
if (strcmp(this->m_s, st.m_s) == 0)
{
return true;
}
return false;
}
bool operator<(const Cstring& st)
{
if (strcmp(this->m_s, st.m_s) < 0)
{
return true;
}
return false;
}
bool operator>(const Cstring& st)
{
if (strcmp(this->m_s, st.m_s) > 0)
{
return true;
}
return false;
}
char operator[](int index)
{
if (index > strlen(this->m_s))
{
return '\0';
}
return this->m_s[index];
}
void display()
{
cout << m_s << endl;
}
~Cstring()
{
delete m_s;
m_s = nullptr;
}
private:
char* m_s;
};
测试代码如下:
int main()
{
//运算符重载
Cstring st = "hello";
Cstring c = "world";
cout << "字符串st与c";
if (st == c)
{
cout << "相等" << endl;
}
else
{
cout << "不相等" << endl;
}
Cstring result=st +" "+ c;
cout << "字符串st与c拼接后";
result.display();
cout << endl;
cout << "st[1]为";
cout << st[1] << endl;
return 0;
}
测试结果如下: