该类实现了C++中string类中定义的基本方法,可以看出其类似于容器。
#include <iostream>
using namespace std;
class CString
{
public:
//带一个默认值参数的构造函数
CString(const char *p = NULL)
{
if(p == NULL)
{
mptr = new char[1]; // new char();
*mptr = '\0';
}
else
{
mptr = new char[strlen(p)+1];
strcpy(mptr, p);
}
}
//拷贝构造函数
CString(const CString &src)
{
mptr = new char[strlen(src.mptr)+1];
strcpy(mptr, src.mptr);
}
//赋值函数
CString& operator=(const CString &src)
{
if(this == &src)
return *this;
delete[] mptr;
mptr = new char[strlen(src.mptr)+1];
strcpy(mptr, src.mptr);
return *this;
}
//析构函数
~CString()
{
delete[] mptr;
mptr = NULL;
}
//>运算符重载函数
bool operator>(const CString &src)const
{
return strcmp(mptr, src.mptr) > 0;
}
//<运算符重载函数
bool operator<(const CString &src)const
{
return strcmp(mptr, src.mptr) < 0;
}
//=运算符重载函数
bool operator==(const CString &src)const
{
return strcmp(mptr, src.mptr) == 0;
}
//求字符串的大小,不包括0
int size()const
{
return strlen(mptr);
}
// operator[]
char& operator[](int index)
{
return *(mptr+index);
}
//将该对象转为字符指针
const char* c_str()const
{
return mptr;
}
//定义迭代器
class iterator
{
public:
iterator(char *p = NULL):ptr(p){}
//迭代器判不等
bool operator!=(const iterator &it)
{
return (ptr != it.ptr);
}
//迭代器前置++运算符重载函数
void operator++()
{
++ptr;
}
//迭代器解引用运算符重载函数
char& operator*()
{
return *ptr;
}
private:
char *ptr;
};
//返回指向字符串首元素的迭代器
iterator begin()
{
return iterator(mptr);
}
//返回指向字符串最后一个元素之后位置的迭代器
iterator end()
{
return iterator(mptr + strlen(mptr));
}
private:
char *mptr;
friend CString operator+(const CString &left, const CString &right);
friend ostream& operator<<(ostream &out, const CString &src);
};
//全局的+运算符重载函数
CString operator+(const CString &left, const CString &right)
{
char *p = new char[strlen(left.mptr) + strlen(right.mptr) + 1];
strcpy(p, left.mptr);
strcat(p, right.mptr);
CString str(p);
delete []p;
return str;
}
//全局的输出运算符重载函数
ostream& operator<<(ostream &out, const CString &src)
{
out<<src.mptr;
return out;
}
VS2015测试:
int main(int argc, char* argv[])
{
//使用带一个默认值参数的构造函数
CString str1;
CString str2 = "aaa";
//使用成员+运算符重载函数和赋值运算符重载函数
CString str3 = str2 + "|";
//使用输出运算符重载函数
cout << str3 << endl;
//测试全局+运算符重载函数和赋值运算符重载函数
str1 = "|" + str2;
str1 = str2 + str3;
cout << str1 << endl;
//测试关系运算符
if (str1 > str2) // > < ==
{
cout << "str1 > str2" << endl;
}
//使用括号运算符重载函数遍历字符串
int size = str1.size();
for (int i = 0; i < size; ++i)
{
cout << str1[i];
}
cout << endl;
//使用迭代器遍历字符串
CString::iterator it = str1.begin();
for (; it != str1.end(); ++it)
{
cout << *it;
}
cout << endl;
//使用String转char*函数
char buf[1024] = { 0 };
strcpy_s(buf, strlen(str1.c_str()) + 1, str1.c_str());
cout << buf << endl;
return 0;
}