C++沉思录读书笔记(二)

来源:互联网 发布:ug经典四轴加工编程 编辑:程序博客网 时间:2024/04/29 13:33
句柄类举例实现
Handle.h头文件:
#ifndef HANDLE_H_H
#define HANDLE_H_H

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;
};


class UseCount
{
public:
UseCount();
UseCount(const UseCount&);
~UseCount();
public:
bool Only();  //描述这个特殊的类UseCount对象是不是唯一指向它的计数器对象
bool Reattach(const UseCount&); 
bool MakeOnly(); //强制这个句柄成为唯一的一个
private:
UseCount & operator = (const UseCount&);
int *uP;
};


class Handle
{
public:
Handle();
Handle(int, int);
Handle(const Point&);
Handle(const Handle&);
Handle& operator = (const Handle&);
~Handle();
int x() const;
    Handle& x(int xv);
int y() const;
Handle& y(int yv);


private:
Point *pP;
UseCount u;   //指向引用计数指针
};
#endif

Handle.cpp实现文件:
#include "Handle.h"
//class Handle 
Handle::Handle() : pP(new Point) { }
Handle::Handle(int x, int y) : pP(new Point(x, y)) { }
Handle::Handle(const Point &p0) : pP(new Point(p0)) { } 
Handle::Handle(const Handle &h) : u(h.u), pP(h.pP) { }


Handle& Handle::operator  = (const Handle& h)
{
if (u.Reattach(h.u))
delete pP;
pP = h.pP;
return *this;
}


Handle::~Handle()
{
if (u.Only())
delete pP;
}
int Handle::x() const
{
return pP->x();
}
Handle& Handle::x(int xv) 
{
if (u.MakeOnly())
{
pP = new Point(*pP);
}
pP->x(xv);
return *this;
}
int Handle::y() const
{
return pP->x();
}
Handle& Handle::y(int yv) 
{
if (u.MakeOnly())
{
pP = new Point(*pP);
}
pP->y(yv);
return *this;
}


//class UseCount
UseCount::UseCount() : uP(new int(1))  { }


UseCount::UseCount(const UseCount& u) : uP(u.uP) {++*uP;}


UseCount::~UseCount()
{
if ( --*uP == 0)
delete uP;
}
bool UseCount::Only()
{
return *uP == 1;
}
bool UseCount::Reattach(const UseCount &u)
{
++*u.uP;
if (--*uP == 0)
{
delete uP;
uP = u.uP;
return false;
}
uP = u.uP;
return false;
}


bool UseCount::MakeOnly()
{
if (*uP == 1)
return false;
--*uP;
uP = new int(1);
return true;
}

TestDeme.cpp:
#include "Handle.h"
using namespace std;

int main(int argc, char* argv[])
{
Point p(3, 4);
Handle h(p);
Handle h2 = h;
h2.x(5);
int n = h.x();
return 0;
}

原创粉丝点击