//第一种
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class String
{
public:
String()
:_str(new char[1])
, _pRefCount(new int(1))
{
_str[0] = '\0';
}
String(char *str)
:_str(new char[strlen(str)+1])
, _pRefCount(new int(1))
{
strcpy(_str, str);
}
String(const String &s)
:_str(s._str)
, _pRefCount(s._pRefCount)
{
(*_pRefCount)++;
}
String &operator=(const String &s)
{
if (this != &s)
{
if (_str&&--(*_pRefCount) == 0)
{
delete[]_str;
delete _pRefCount;
}
_str = s._str;
_pRefCount = s._pRefCount;
++(*s._pRefCount);
}
return *this;
}
~String()
{
Relase();
}
void Relase()
{
if (_str&&--(*_pRefCount) == 0)
{
delete[]_str;
delete _pRefCount;
}
}
char &operator[](size_t index)
{
if (*_pRefCount >1)
{
--(*_pRefCount);
char *tmp = new char[strlen(_str) + 1];
strcpy(tmp, _str);
_str = tmp;
_pRefCount = new int(1);
}
return _str[index];
}
friend ostream &operator<<(ostream &os, String &s);
private:
char *_str;
int *_pRefCount; //引用计数
};
ostream &operator<<(ostream &os, String &s)
{
os << s._str << endl;;
return os;
}
int main()
{
String op1("abcd");
String op2 = op1;
String op3("AB");
String op4 = op3;
op3 = op1;
cout <<"op1="<< op1 << endl;
cout << "op2=" << op2 << endl;
cout << "op3=" << op3 << endl;
cout << "op4=" << op4 << endl;
op3[0] = 'x';
cout << "op1=" << op1 << endl;
cout << "op2=" << op2 << endl;
cout << "op3=" << op3 << endl;
cout << "op4=" << op4 << endl;
system("pause");
return 0;
}
//优化版本 //把计数与字符串所需的空间开辟在一起,该空间的前四个字节存计数值
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class String
{
public:
String()
:_str(new char[5])
{
*_str = 1;
_str += 4;
*_str = '\0';
}
String(char *str)
:_str(new char[strlen(str) + 5])
{
*(int *)_str = 1;
_str += 4;
strcpy(_str, str);
}
String(const String &s)
:_str(s._str)
{
(*(int *)(_str - 4))++;
}
String &operator=(const String &s)
{
if (this != &s)
{
if (_str&&--(*(int *)(_str - 4)) == 0)
{
delete[](_str - 4);
}
_str = s._str;
*(int *)(_str - 4) = *(int *)s._str;
}
return *this;
}
~String()
{
Relase();
}
void Relase()
{
if (_str&&--*(int *)(_str-4) == 0)
{
delete[](_str-4);
}
}
char &operator[](size_t index)
{
if (*(int*)(_str - 4) >1)
{
(*(int *)(_str - 4))--;
char *tmp = new char[strlen(_str) + 5];
(*(int *)(tmp)) = 1;
tmp += 4;
strcpy(tmp, _str);
_str = tmp;
}
return _str[index];
}
friend ostream &operator<<(ostream &os, String &s);
private:
char *_str;
};
ostream &operator<<(ostream &os, String &s)
{
os << s._str<< endl;
return os;
}
int main()
{
String op1("abcd");
String op2 = op1;
String op3("AB");
String op4 = op3;
op3 = op1;
cout << "op1=" << op1 << endl;
cout << "op2=" << op2 << endl;
cout << "op3=" << op3 << endl;
cout << "op4=" << op4 << endl;
op3[0] = 'A';
cout << "op1=" << op1 << endl;
cout << "op2=" << op2 << endl;
cout << "op3=" << op3 << endl;
cout << "op4=" << op4 << endl;
system("pause");
return 0;
}