String类的实现
//#include<string>
#include<iostream>
using namespace std;
class String
{
private:
char* _pstr;
friend String operator+(const String& s1, const String& s2);
friend ostream& operator<<(ostream& out, const String& str);
public:
String(const char* p = nullptr)
{
if (p != nullptr)
{
_pstr = new char[strlen(p) + 1];
strcpy(_pstr, p);
}
else
{
_pstr = new char('\0');
}
}
~String()
{
delete[]_pstr;
_pstr = nullptr;
}
String(const String& s)
{
_pstr = new char[strlen(s._pstr) + 1];
strcpy(_pstr, s._pstr);
}
String & operator=(const String &src)
{
if (&src == this)
{
return *this;
}
delete[]_pstr;
_pstr = new char[strlen(src._pstr) + 1];
strcpy(_pstr, src._pstr);
return *this;
}
char& operator[](int i) //可以作为左值,被修改
{
return _pstr[i];
}
const char& operator[](int i) const //常方法,String不可被修改
{
return _pstr[i];
}
bool operator>(const String& s)const
{
return strcmp(this->_pstr, s._pstr) > 0;
}
bool operator<(const String& s)const
{
return strcmp(this->_pstr, s._pstr) < 0;
}
bool operator==(const String& s)const
{
return strcmp(this->_pstr, s._pstr) == 0;
}
int length()const
{
return strlen(_pstr);
}
};
String operator+(const String& s1, const String& s2)
{
//为了避免内存泄漏,先构造一个String对象,再释放_s的空间,返回String对象
char* _s = new char[strlen(s1._pstr) + strlen(s2._pstr) + 1];
strcpy(_s, s1._pstr);
strcat(_s, s2._pstr);
String s(_s);
delete[]_s;
return s;
}
ostream& operator<<(ostream& out, const String& str)
{
out << str._pstr;
return out;
}
int main()
{
String s1 = "aaa";
String s2 = "bbb";
String s3 = s1 + s2;
cout << s3 << endl;
cout << (s2 > s1) << endl;
cout << s1.length() << endl;
for (int i = 0; i < s1.length(); i++)
{
cout << s1[i] << " ";
s1[i] = s2[i];
}
cout << s1;
}
下述代码中,为了返回两字符串相连的结果,_s和s内部的调用分别做了一次new和delete,同时return时s做了一次拷贝构造,代价较高。
String operator+(const String& s1, const String& s2)
{
//为了避免内存泄漏,先构造一个String对象,再释放_s的空间,返回String对象
char* _s = new char[strlen(s1._pstr) + strlen(s2._pstr) + 1];
strcpy(_s, s1._pstr);
strcat(_s, s2._pstr);
String s(_s);
delete[]_s;
return s;
}
一种更优解法
String operator+(const String& s1, const String& s2)
{
//减少了一次new和一次delete
String tmp;
tmp._pstr = new char[strlen(s1._pstr) + strlen(s2._pstr) + 1];
strcpy(tmp._pstr, s1._pstr);
strcat(tmp._pstr, s2._pstr);
return tmp;
}
标签:pstr,const,String,实现,s2,s1,21String,._
From: https://www.cnblogs.com/sio2zyh/p/17977360