大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
当要创建的对象的内容与一个已经创建的对象内容相同时,无需再重新输入相同参数创建对象,可以利用拷贝构造函数创建已知对象的拷贝。
ProtoType所提供的接口就是对自身拷贝构造函数的封装。

#include <iostream>

using namespace std;

//ProtoType基类
class ProtoType
{
public:
    ProtoType(
int i):index(i){}
    
virtual ProtoType* Clone() = 0;
    
int index;
}
;    

//具体ProtoType子类
class ConcreteProtoType: public ProtoType
{
public:
    ConcreteProtoType(
int i):ProtoType(i){}

    
//调用拷贝构造函数返回自身对象的拷贝
    ProtoType* Clone()
    
{
        
return new ConcreteProtoType(*this);
    }

}
;


int main()
{
    ProtoType
* p = new ConcreteProtoType(3);
    
//pc指向的是已创建对象的拷贝
    ProtoType* pc = p->Clone();

    cout
<<p->index<<endl;
    cout
<<pc->index<<endl;

    delete pc;
    delete p;

    
return 0;
}
posted on 2009-06-09 09:59 大胖 阅读(113) 评论(0)  编辑 收藏 引用 所属分类: Design Pattern

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理