Java 参考: http://c.biancheng.net/view/1343.html
#include <iostream>
using namespace std;
class TSharp
{
public:
TSharp():mArea(0){}
double mArea;
virtual TSharp *Clone() = 0;
void PrintArea()
{
cout << "mArea is " << mArea << endl;
}
virtual void CalcArea(){}
};
class TRectangle:public TSharp
{
public:
TRectangle():mWidth(0),mHight(0){}
double mWidth;
double mHight;
TRectangle *Clone()
{
TRectangle* pst = new TRectangle();
pst->mHight = mHight;
pst->mWidth = mWidth;
pst->mArea = mArea;
return pst;
}
virtual void CalcArea()
{
mArea = mWidth * mHight;
cout << mArea << endl;
}
};
int main()
{
cout << "enter" << endl;
TRectangle *pstTRectangle = new TRectangle();
if (nullptr == pstTRectangle)
{
cout << "clone TRectangle failed." << endl;
return -1;
}
pstTRectangle->mWidth = 10;
pstTRectangle->mHight = 2;
pstTRectangle->CalcArea();
pstTRectangle->PrintArea();
TRectangle *pstQuadrate = pstTRectangle->Clone();
if (nullptr == pstQuadrate)
{
cout << "clone pstQuadrate failed." << endl;
delete pstTRectangle;
pstTRectangle = nullptr;
return -1;
}
pstQuadrate->mHight = 10;
pstQuadrate->CalcArea();
pstQuadrate->PrintArea();
delete pstQuadrate;
pstQuadrate = nullptr;
delete pstTRectangle;
pstTRectangle = nullptr;
cout << "exit" << endl;
return 0;
};
执行结果
PS E:\workspace\sample\Prototype> g++ .\prototype.cpp
PS E:\workspace\sample\Prototype> ./a
enter
20
mArea is 20
100
mArea is 100
exit