参考代码:
#include<iostream>
#include<string>
using namespace std;
class B{
public:
B(){}
B(const string &n):name(n){}
B(const char *n):name(n){}
string getname(void) const{
return name;
}
B(const B &b){
name = b.getname();
}
void set(const string a){
name = a;
}
private:
string name;
};
class handle;
class Temp{
friend class handle;
public:
Temp():count(1){}
Temp(const string &a):b(a),count(1){}
Temp(const char * a):b(a),count(1){}
private:
class B b;
int count;
};
class handle{
friend ostream& operator<<(ostream &os, const handle& a);
public:
handle():T(new Temp){}
handle(const char *a):T(new Temp(a)){}
handle(const string &a):T(new Temp(a)){}
handle(const handle& h){
h.T->count++;
T=h.T;
}
handle& operator=(const handle&h){
if(T == h.T)
{
return *this;
}
else
{
h.T->count++;
if(--T->count == 0)
delete T;
T = h.T;
return *this;
}
}
string getstring() const{
return T->b.getname();
}
void setstring(const string& a)
{
if( T->count !=1)
{
--T->count;
T = new Temp(a);
}
else
T->b.set(a);
}
int getnum () const
{
return T->count;
}
~handle(){
if(T)
{
if( --T->count == 0)
delete T;
}
}
private:
Temp *T;
};
ostream& operator<<(ostream &os, const handle& a)
{
os<<a.getstring();
return os;
}
int main()
{
handle h1("good");
handle h2 = h1;
handle h4;
h4 = h1;
cout<<h1<<endl;
cout<<h1.getnum()<<endl;
cout<<h4<<endl;
cout<<h4.getnum()<<endl;
h4.setstring("ok");
cout<<h1<<endl;
cout<<h1.getnum()<<endl;
cout<<h4<<endl;
cout<<h4.getnum()<<endl;
return 0;
}