• 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;

    }

  • 相关阅读:
    ubuntu下如何卸载nvidia显卡驱动?
    如何加速编译linux内核模块?
    ubuntu下编译linux内核之前需要做哪些准备?
    ubuntu最近升级到最新的linux内核后,网络无法使用怎么办?
    ubuntu下如何高速下载?
    linux配置java环境变量(详细)
    Javascript 中 == 和 === 区别是什么?
    mybatis 根据多个id查询数据 foreach标签
    mybatis多参数查询问题:org.apache.ibatis.binding.BindingException: Parameter 'name' not found. Available par
    Java Array二维数组使用
  • 原文地址:https://www.cnblogs.com/revenge/p/4896297.html
Copyright © 2020-2023  润新知