一个简单的point坐标类
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, yval;
};
将handle 绑定到其上 进行一层封装
通过handle控制那些操作可以公开 那些操作私有 阻止用户对point的地址的操作
更重要的是提供 point的引用计数 将多个handle绑定到ppint上 当全部释放对point的使用权时
才进行释放point的操作
那么增加两个类
一个引用计数类 class UPoint
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句柄类 包含UPoint的指针 构造和析构的时候会将计数+1
当计数到0 则释放指针内存
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;
};
全部代码如下:
// sample0.cpp: 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <iostream> class Point {
public:
Point():xval(),yval(){}
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, yval;
}; class UPoint {
friend class Handle;
Point p;
int u; UPoint() :u() {}
UPoint(int x, int y) :p(x, y), u() {}
UPoint(const Point& p0):p(p0),u(){}
}; 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 == )
delete up;
} Handle::Handle(const Handle& h) :up(h.up) { ++up->u; }
Handle& Handle::operator=(const Handle& h) {
++h.up->u;
if (--up->u == ) {
delete 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()
{
Handle h;
std::cout << h.x() << " " << h.y() << std::endl;
return ;
}