string 类操作的重载实现
class CMyString
{
public:
CMyString(char *ptr = NULL)
{
if (ptr == NULL)
{
mpStr = new char[1];
*mpStr = '\0';
}
else
{
mpStr = new char[strlen(ptr) + 1];
strcpy(mpStr, ptr);
}
}
~CMyString()
{
delete[]mpStr;
mpStr = NULL;
}
CMyString(const CMyString &src)
{
mpStr = new char[src.length() + 1];
strcpy(mpStr, src.mpStr);
}
CMyString& operator=(const CMyString &src)
{
if (this == &src)
{
return*this;
}
delete[]mpStr;
mpStr = NULL;
mpStr = new char[src.length() + 1];
strcpy(mpStr, src.mpStr);
return *this;
}
bool operator>(const CMyString&src){ return strcmp(mpStr, src.mpStr) > 0; }
bool operator<(const CMyString&src){ return strcmp(mpStr, src.mpStr) < 0; }
bool operator==(const CMyString&src){ return strcmp(mpStr, src.mpStr) == 0; }
bool operator!=(const CMyString&src){ return strcmp(mpStr, src.mpStr) != 0; }
char operator[](int index)
{
return mpStr[index];
}
int length()const{ return strlen(mpStr); }
const char* c_str()const{ return mpStr; }
// 定义当前CMyString类型的迭代器
class iterator
{
public:
iterator(char *ptr = NULL) :_ptr(ptr){}
/*iterator(char *ptr = NULL, int pos = 0)
{
_ptr = _ptr + pos;
}*/
// 构造函数 operator!= operator++ operator*
bool operator!=(const iterator &it)
{
return _ptr != it._ptr;
}
void operator++()
{
_ptr++;
}
char& operator*()
{
return *_ptr;
}
private:
// 迭代器的成员变量
char *_ptr;
};
iterator begin(){ return iterator(mpStr); } // return第0号位元素的迭代器表示
iterator end(){ return iterator(mpStr + length()); } // return最后一位元素的迭代器表示
private:
char *mpStr;
friend CMyString operator+(const CMyString &lhs,const CMyString &rhs);
friend ostream& operator<<(ostream&out, const CMyString&src);
friend istream& operator>>(istream&in, CMyString&src);
};
CMyString operator+(const CMyString &lhs, const CMyString &rhs)
{
char*ptmp = new char[lhs.length() + rhs.length() + 1];
strcpy(ptmp, lhs.mpStr);
strcat(ptmp, rhs.mpStr);
CMyString tmp(ptmp);
delete ptmp;
return tmp;
}
ostream& operator<<(ostream&out, const CMyString&src)
{
out << src.mpStr << endl;
return out;
}
istream& operator>>(istream&in, CMyString&src)
{
char buff[1024] = {0};
in >> buff;
delete[]src.mpStr;
src.mpStr = new char[strlen(buff) + 1];
strcpy(src.mpStr, buff);
return in;
}
// operator<< operator>>
int main()
{
CMyString str1;
CMyString str2 = "aaa";
CMyString str3 = "bbb";
CMyString str4 = str2 + str3;
cout << str4 << endl;
str4 = str2 + "ccc";
cout << str4 << endl;
str4 = "ddd" + str2;
cout << str4 << endl;
cout << "请输入一段字符串:";
cin >> str4;
cout << "你输入的字符串是:" << str4 << endl;
if (str2 > str3)
{
cout << "str2 > str3" << endl;
}
else
{
cout << "str2 <= str3" << endl;
}
int size = str4.length();
for (int i = 0; i < size; ++i)
{
cout << str4[i];
}
cout << endl;
char buffer[1024] = { 0 };
strcpy(buffer, str4.c_str());
cout << "buffer:" << buffer << endl;
CMyString testStr = "hello world";
CMyString::iterator it = testStr.begin(); // begin()返回第0个元素的迭代器
for (; it != testStr.end(); ++it)// testStr.end()返回最后一个元素的后继位置
{
cout << *it << " ";
}
cout << endl;
return 0;
}
运行结果如下: