您的位置:首页 > 编程语言 > C语言/C++

C++中String类的实现

2018-02-18 20:26 204 查看
要注意字符串是否为空

代码实现:

#include <iostream>
using namespace std;

#include <string.h>

class CString
{
public:
CString(char* p = "")//构造函数
{
mstr = new char[strlen(p) + 1]();
strcpy(mstr, p);
}
CString(const CString& rhs)//拷贝构造函数
{
mstr = new char[strlen(rhs.mstr) + 1]();
strcpy(mstr, rhs.mstr);
}
~CString()//析构函数
{
delete mstr;
mstr = NULL;
}
CString& operator=(const CString& rhs)//赋值运算符的重载函数
{
if (this != &rhs)
{
delete mstr;
mstr = new char[strlen(rhs.mstr) + 1];
strcpy(mstr, rhs.mstr);
}
return *this;
}
bool operator !=(const CString& rhs)//重载!=
{
return strcmp(mstr, rhs.mstr) != 0;
}
bool operator ==(const CString& rhs)//重载==
{
return !(*this != rhs);
}

private:
char* mstr;
friend istream& operator >>(istream&, CString&);//重载输入流运算符
friend const CString operator+(const CString&, const CString&);//重载+
friend ostream& operator<<(ostream&, const CString&);//重载输出流运算符
};

//类外实现重载输入流运算符
istream& operator >>(istream& in, CString& rhs)
{
char *p = new char[100]();
in >> p;
int i = 0;
if (p[99] == '0')
{
i = strlen(p);
}
else
{
i = 100;
}
delete rhs.mstr;
rhs.mstr = new char[i + 1]();
strcpy(rhs.mstr, p);
return in;
}

//类外实现重载+
const CString operator+(const CString& lhs, const CString& rhs)
{
char* tmp = new char[strlen(lhs.mstr) + strlen(rhs.mstr) + 1]();
strcat(tmp, lhs.mstr);
strcat(tmp, rhs.mstr);
return CString(tmp);
}

//类外实现重载输出流运算符
ostream& operator<<(ostream& out, const CString& rhs)
{
out << rhs.mstr << " ";
return out;
}

int main()
{
CString str1;
CString str2("hello");
CString str3(str2);
cout << "str1:";
cin >> str1;
str3 = "hello";
str3 = str3 + "world";
cout << "str2:" << str2 << endl;
cout <<"str3:" << str3 << endl;

return 0;
}

string类是C++中很重要的类 一定要掌握 面试的时候会问到

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: