zoukankan      html  css  js  c++  java
  • prototype原型(待完善)

    模式: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;

    }

  • 相关阅读:
    第32章 数据库的备份和恢复
    Perl 打印关键字上下行
    mysql select * into OUTFILE 不会锁表
    独享表空间 ibdata1
    sql 使用单引号
    Oracle 维护常用SQL
    Mysql 独享表空间
    Mysql Perl unload表数据
    PLSQL 拼接SQL
    begin和declare
  • 原文地址:https://www.cnblogs.com/revenge/p/4896297.html
Copyright © 2011-2022 走看看