标签:
模式: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;
}
标签:
原文地址:http://www.cnblogs.com/revenge/p/4896297.html