///句柄:什么是句柄??? ////用于控制对一个对象的多次利用,而又不去复制它?! ////有时候复制一个对象的代价是非常的大的。 class Point { public: Point(): xval(0),yval(0){} Point(int x,int y): xval(x),yval(y){} int x() const {return xval;} int y() const {return yval;} Point& x(int xv){xval = xv; return *this;} Point& y(int yv){yval = yv;return *this;} private: int xval; int yval; }; /////let see the class of UPoint /////引入UPoint 只是为了在Point类中添加一个引用计数 class Handle; class Upoint { friend class Handle; Point p; int u; Upoint(): u(1){} Upoint(int x,int y): p(x,y),u(1){} Upoint(const Point& p0): p(p0),u(1){} }; /////先看Handle是怎样实现的,in there the function ///about x() and y() in order to operator the Point class Handle { public: Handle(); Handle(int ,int); Handle(const Point&); Handle(const Handle&); Handle& operator=(const Handle&); ~Handle(); int x() const; Handle& x(int); int y() const; Handle& y(int); private: Upoint *up; }; Handle::Handle():up(new Upoint){} Handle::Handle(int x,int y):up(new Upoint(x,y)){} Handle::Handle(const Point& p):up(new Upoint(p)){} Handle::~Handle() { if(--up->u==0) delete up; } Handle::Handle(const Handle& h):up(h.up){++up->u;} Handle& Handle::operator=(const Handle& h) { ++h.up->u; if(--up->u==0) delete up; up = h.up; return *this; } int Handle::x() const { return up->p.x(); } int Handle::y() const { return up->p.y(); } Handle& Handle::x(int x0) { up->p.x(x0); return *this; } Handle& Handle::y(int y0) { up->p.y(y0); return *this; } int main(int argc, char* argv[]) { Point p(2,3); Handle h0(p); Handle h1(h0); Handle h2(h0); cout<<h1.x()<<endl; return 0; }