句柄的使用

#include <iostream>
class Point{
public:
Point():xv(
0),yv(0){}
Point(
int a, int b):xv(a), yv(b){}
Point(
const Point &p):xv(p.xv), yv(p.yv){}
int x() const {return xv;}
int y() const {return yv;}
Point
& x(int x){xv = x; return *this;}
Point
& y(int y){yv = y; return *this;}
private:
int xv;
int yv;
};
class Point3D:public Point{
public:
Point3D():zv(
0){}
private:
int zv;
};

class Handler{
public:
Handler():p(
0), use(new int(1)){}
Handler(
const Point &p0):p(new Point(p0)), use(new int(1)){};//必须new
Handler(const Handler &i):p(i.p), use(i.use){++*use;}
~Handler(){decr_use();}
Handler
& operator=(const Handler &);
Point
* operator->()const{if(p)return p;}//这里可以是const的,那样的话就不能改变point内的值了
Point & operator*()const{if(p)return *p;}

private:
Point
*p;
int *use;
void decr_use()
{
if(--*use == 0){delete p; delete use;}}

};
/*
Handler::Handler(const Point &point)
{
p = point;
use = 1;
}
*/
Handler
&
Handler::
operator=(const Handler &h)
{
++*h.use;
decr_use();
p
= h.p;
use
= h.use;
return *this;
}
main()
{
Point p(
1,2);

Handler h(p);
Point3D p3d;
h
= p3d;
h
->x(6);
h
->y(6);
cout
<<"point x = "<<h->x()<<" point y = "<<h->y()<<endl;
}

一个简单的句柄例子,注意注释里的几点。

C++语言的一个问题就是不支持使用对象进行面向对象编程,而是必须使用指针和引用。常用的解决方案是句柄和包装。句柄类存储和管理基类的指针,指针指向锁只对象的类型是可以变化的,既可以指向基类也可以指向派生类,用户通过句柄来访问继承层次的操作。句柄带来的好处就是可以获得动态行为,但无需操心指针的管理。

posted @ 2011-02-25 14:34  macula7  阅读(743)  评论(0编辑  收藏  举报