模式:prototype  解决向量的深浅克隆

#pragma once

#ifndef _PROTOTYPE_H_

#define _PROTOTYPE_H_

class Prototype{

public:

virtual ~Prototype();

virtual Prototype* Clone() const = 0;

virtual void showData() = 0;

virtual void addOne() = 0;

protected:

Prototype();

public:

int *p;

};

class ConcretePrototype :public Prototype{

public:

ConcretePrototype();

ConcretePrototype(const ConcretePrototype& cp);

~ConcretePrototype();

Prototype* Clone() const;

void showData();

void addOne();

};

#endif //~_PROTOTYPE_H_

#include "prototype.h"

//Prototype.cpp

#include "Prototype.h"

#include <iostream>

using namespace std;

Prototype::Prototype(){

}

Prototype::~Prototype(){

}

Prototype* Prototype::Clone() const{

return 0;

}

ConcretePrototype::ConcretePrototype(){

this->p = new int[5];

for (int i = 0; i < 5; i++)

p[i] = i;

}

ConcretePrototype::~ConcretePrototype(){

delete[] p;

}

ConcretePrototype::ConcretePrototype(const ConcretePrototype& cp){

cout << "ConcretePrototype copy ..." << endl;

//浅赋值

this->p = cp.p;

//深赋值

/*this->p = new int[5];

int i;

for(i = 0; i < 5;i++)

this->p[i] = cp.p[i];*/

}

Prototype* ConcretePrototype::Clone() const{

return new ConcretePrototype(*this);

}

void ConcretePrototype::showData()

{

int i;

cout << "<";

for (i = 0; i < 2; i++)

cout <<p[i] << ",";

cout << ">";

}

void ConcretePrototype::addOne()

{

int i;

for (i = 0; i < 2; i++)

p[i] += 10;

}

#include "Prototype.h"

#include <iostream>

using namespace std;

int main(int argc, char* argv[]){

Prototype* p = new ConcretePrototype();

Prototype* p1 = p->Clone();

cout << "Before:" << endl;

cout << "p:";

p->showData();

cout << endl;

cout << "p1:";

p1->showData();

cout << endl;

p1->addOne();

cout << "After:" << endl;

cout << "p:";

p->showData();

cout << endl;

cout << "p1:";

p1->showData();

cout << endl;

system("pause");

cin.get();

return 0;

}

最新文章

  1. [No0000A0]批处理命令学习之:常用的特殊符号
  2. jdbcTemplate 泛型 查询
  3. 2437: [Noi2011]兔兔与蛋蛋 - BZOJ
  4. mysql5.7的安装
  5. Codevs 1648 最大和
  6. Python的面向对象4
  7. NewRowNeeded和UserAddedRow事件以及RowsAdded的区别使用
  8. [转]IDENT_CURRENT、SCOPE_IDENTITY、@@IDENTITY 差異對照表
  9. 数学之路-python计算实战(19)-机器视觉-卷积滤波
  10. 【夸QT十一】外来物品:通用脚本帮助Web运行基础Linux命令
  11. i春秋与我
  12. 创建一个可用的简单的SpringMVC项目,图文并茂
  13. Saltstack_使用指南06_远程执行-指定目标
  14. tex中pdf外链
  15. C#中关键字 &#39;User&#39; 附近有语法错误
  16. windows 7 安装时提示:安装程序无法创建新的系统分区
  17. C6.cpp
  18. 第二节,surf特征检测关键点,实现图片拼接
  19. 百度AI搜索引擎
  20. blfs(systemd版本)学习笔记-wget的安装与配置

热门文章

  1. 【VSC】我安装了哪些扩展插件
  2. MapReduce操作Hbase --table2file
  3. Linux基础命令之文件过滤及内容编辑处理(一)
  4. jQuery----淘宝商品展示(类似与tab切换)
  5. 记一次ss无法上网的排查
  6. Mac配置虚拟主机
  7. 20155211 Exp1 PC平台逆向破解(5)M
  8. 20154327 Exp9 Web安全基础
  9. 【LNOI2014】LCA
  10. Unity3d之Hash&amp;Slash学习笔记之(二)--角色基础类的构建