#include <iostream>
#include <string.h>
using namespace std;
class String;
// 封裝一個計數器的類來維護,可以隱藏起來,即使用者不必關心是如何實現的
class String_Rep
{
friend class String;
public:
String_Rep(const char *str = " ") :count(0)
{
m_data = new char[strlen(str) + 1];
strcpy(m_data, str);
}
~String_Rep()
{
delete[]m_data;
}
public:
void increment()
{
count++;
}
void decrement()
{
if (--count == 0)
{
delete this;// 哪一個rep的count為0了釋放當時的rep
}
}
private:
char *m_data;
int count;
};
//////////////////////////////////////////////////////////////////////
class String
{
public:
String(const char *str = " ") :rep(new String_Rep(str))
{
rep->increment();
}
String(const String &s) :rep(s.rep)
{
rep->increment();
}
String& operator=(const String &s)
{
if (this != &s)
{
rep->decrement();// 迭代器
rep = s.rep;
rep->increment();
}
return *this;
}
~String()
{
rep->decrement();
}
public:
void print()const
{
cout << rep->m_data << endl;
}
private:
String_Rep *rep;// 控制程式碼
};
int main()
{
String s1("hello");
String s2;
s2 = s1;
String s3("world");
String s4;
s4 = s3;
s1.print();
s2.print();
s3.print();
s4.print();
return 0;
}