访客地图

对象代理

张成
2014/10

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
class Point
{
public:
    virtual Point* copy() const=0;
    virtual int weight() const = 0;
};
class PointX:public Point
{
    virtual PointX* copy() const
    {
        return new PointX(*this);
    }
    virtual int weight() const{
        return 1;
    }
};
class PointSurrogate
{
public:
    PointSurrogate();
    PointSurrogate(const Point& p);
    ~PointSurrogate();
    PointSurrogate(const PointSurrogate& ps);
    PointSurrogate& operator=(const PointSurrogate& ps);
    int weight()const;
private:
    Point* vp;
};
PointSurrogate::PointSurrogate():vp(0)
{
}
PointSurrogate::PointSurrogate(const Point& v):
    vp(v.copy())
{
}
PointSurrogate::~PointSurrogate()
{
    delete vp;
}
PointSurrogate::PointSurrogate(const PointSurrogate& v):
    vp(v.vp?v.vp->copy():0)
{
}
PointSurrogate& PointSurrogate::operator=(const PointSurrogate& v)
{
    if (this != &v)
    {
        delete vp;
        vp = v.vp?v.vp->copy(): 0;
    }
    return *this;
}
int PointSurrogate::weight()const
{
    if (vp == 0)
        throw "null obj";
    return vp->weight();
}
int _tmain(int argc, _TCHAR* argv[])
{
    int i=0;
    PointSurrogate point_lot[10];
    PointX x;
    point_lot[i++] = x;
    printf("%d",point_lot[0].weight());
    return 0;
}