首页 > 编程语言 >C++设计模式-(创建模式)原型模式

C++设计模式-(创建模式)原型模式

时间:2022-11-13 16:59:35浏览次数:35  
标签:virtual C++ 原型 模式 animal 设计模式 eat

 

原型模式主要用于 复制当前对象的副本 

#include<iostream>
class animal
{
public:
    virtual ~animal()
    {}
    virtual void eat()
    {
        std::cout << "不确定" << std::endl;
    }
    //克隆函数
    virtual animal* clone()
    {
        animal* t = new animal();
        //一些成员复制
        return t;
    }
};

class  tiger :public animal
{
    virtual ~tiger()
    {
    }
    virtual void eat()
    {
        std::cout << "吃肉" << std::endl;
    }
    //克隆函数
    virtual tiger* clone()
    {
        
        tiger* t = new tiger;
        //一些成员复制
        return t;
    }
};

class sheep :public animal
{
    virtual ~sheep()
    {}
    virtual void eat()
    {
        std::cout << "吃草" << std::endl;
    }
    //克隆函数
    virtual sheep* clone()
    {
        sheep* t = new sheep;
        //一些成员复制
        return t;
    }
};

int main()
{
    //下面是使用克隆的方式 
  //也就是原型模式
animal* a = new tiger; a->eat(); animal* a2 = a->clone(); a2->eat(); //下面是使用拷贝构造的方式 animal* a3 = new animal(*a); a3->eat(); return 0; }

 

标签:virtual,C++,原型,模式,animal,设计模式,eat
From: https://www.cnblogs.com/atggg/p/16886260.html

相关文章

  • 按照C++语言程序结构组成数字电路进行计算的计算机
    按照C++语言程序结构组成数字电路进行计算的计算机按照C++语言程序结构组成数字电路进行计算的计算机是一种可以按照C++语言程序结构来安排加法器,输出显示电路,输入电路,的数......
  • 类和对象——C++运算符重载
    概念:对已有的运算符重新定义,赋予其另一种功能,以适应不同数据类型。。重载的两类方法:1.类成员函数重载2.全局函数重载注意:运算符重载也可以实现函数重载引入:我们希望......
  • C++ template using for what?
    //Forclassusing,youcansetaseriousofmacrotopredictsomething////whenyoucallthismacro,thetemplatecouldmakeanewfunctionbyyourinput//templ......
  • 4.流控模式(关联和链路)
    1.流控模式在添加限流规则时,点击高级选项,可以选择三种流控模式:直接:统计当前资源的请求,触发阈值时对当前资源直接限流,也是默认的模式关联:统计与当前资源相关的另一个资......
  • C++运算符重载相关知识点
    1.运算符重载限制重载后的运算符必须至少有一个操作数是用户自定义的类型使用运算符时不能违反运算符原来的句法规则,也不能修改运算符的优先级。2.不能进行重载的运......
  • C++之string的底层简单实现!(七千字长文详解)
    C++之string的底层简单实现!string之私有成员变量namespaceMySTL{classstring {private: char*_str; size_t_size; size_t_capacity; //这里capa......
  • 周日1040C++班级2022-11-13 数据类型-字符型char
    数据类型-char字符型特点:由单引号’’构成,且长度为1,在格式化中字符用%c来表示正确的字符:‘a’ ‘ ’ ‘#’ ‘1’错误的字符:’aa’ ‘##’ ‘’’’ascii码表......
  • CSP 202203-1 未初始化警告 C++
    1#include<iostream>2#include<vector>3intmain(){4intx{},y{};5std::cin>>x>>y;//读入第一行6std::vector<std::vector<int>>k......
  • 11.vim模式使用过程中常用快捷键
    一.普通模式#1.命令光标跳转G      #光标跳转至末端gg     #光标跳转至顶端Ngg    #光标跳转至当前文件内的N行$      #光......
  • (作者推荐)【RocketMQ入门到精通】— RocketMQ中级特性能力 | ​长轮询Pull和Push模式
    名言警句任何先进的技术均与魔法无异追本溯源【​​经历了6个月的失踪,我将带着干货终究归来!【RocketMQ入门到精通】​​】RocketMQ消费机制回顾   在众多MQ的体系中,一......