句柄的使用

#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++语言的一个问题就是不支持使用对象进行面向对象编程,而是必须使用指针和引用。常用的解决方案是句柄和包装。句柄类存储和管理基类的指针,指针指向锁只对象的类型是可以变化的,既可以指向基类也可以指向派生类,用户通过句柄来访问继承层次的操作。句柄带来的好处就是可以获得动态行为,但无需操心指针的管理。
原文链接: https://www.cnblogs.com/macula7/archive/2011/02/25/1964851.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/21549

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午11:31
下一篇 2023年2月7日 下午11:31

相关推荐