64,654
社区成员
发帖
与我相关
我的任务
分享
// 2013041701.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
// 实体类
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;
};
// 计数器类
class UseCount{
public:
UseCount();
UseCount(const UseCount&);
UseCount& operator=(const UseCount&);
~UseCount();
bool only();
bool reattach(const UseCount&);
bool make_only();
private:
int *p;
};
UseCount::UseCount():p(new int(1))
{
}
UseCount::UseCount(const UseCount& other):p(other.p)
{
++*p;
}
UseCount::~UseCount()
{
if(--*p==0)
delete p;
}
bool UseCount::only()
{
return *p==1;
}
bool UseCount::reattach(const UseCount& other)
{
// 先递增右边
++*other.p;
// 判断左边
if(--*p==0)
{
delete p;
p = other.p;
return true;
}
p = other.p;
return false;
}
bool UseCount::make_only()
{
if(*p==1)
return false;
--*p;
p = new int(1);
return true;
}
// 定义句柄类
class Handle{
public:
Handle();
Handle(int xv, int yv);
Handle(const Point& p0);
Handle(const Handle& h);
Handle& operator=(const Handle& other);
~Handle();
int x() const;
int y() const;
Handle& x(int xv);
Handle& y(int yv);
private:
Point *p;
UseCount u;
};
Handle::Handle():p(new Point)
{
}
Handle::Handle(int xv, int yv):p(new Point(xv, yv))
{
}
Handle::Handle(const Point& p0):p(new Point(p0))
{
}
Handle::Handle(const Handle& h):u(h.u),p(h.p)
{
}
Handle::~Handle()
{
if(u.only())
delete p;
}
Handle& Handle::operator=(const Handle& h)
{
if(u.reattach(h.u))
delete p;
p = h.p;
return *this;
}
int Handle::x() const
{
return p->x();
}
int Handle::y() const
{
return p->y();
}
Handle& Handle::x(int xv)
{
/**
if(*p==1)
return false;
--*p;
p = new int(1);
return true;
*/
if(u.make_only())
p = new Point(*p); // p是point
p->x(xv);
return *this;
}
Handle& Handle::y(int y0)
{
if (u.make_only()) // 就是这里 为什么用先用make_only 然后p=new Point(*p)?p和*p指的是一个吗
p=new Point(*p); // 这一句和上一句
p->y(y0);
return *this;
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}