zoukankan      html  css  js  c++  java
  • 如何实现 Copying derived entities using only base class pointer

    #include <iostream>
    
    struct CloneableBase {
        virtual CloneableBase* clone() const = 0;
    };
    
    
    template<class Derived>
    struct Cloneable : CloneableBase {
        virtual CloneableBase* clone() const {
            return new Derived(static_cast<const Derived&>(*this));
        }   
    };
    
    
    struct D1 : Cloneable<D1> {
        D1() {}
        D1(const D1& other) {
            std::cout << "Copy constructing D1
    ";
        }   
    };
    
    struct D2 : Cloneable<D2> {
        D2() {}
        D2(const D2& other) {
            std::cout << "Copy constructing D2
    ";
        }   
    };
    
    
    int main() {
        CloneableBase* a = new D1();
        CloneableBase* b = a->clone();
        CloneableBase* c = new D2();
        CloneableBase* d = c->clone();
    }

    http://stackoverflow.com/questions/5027456/copying-derived-entities-using-only-base-class-pointers-without-exhaustive-tes

    static_cast<const Derived&> 注意这里,因为函数的参数就是引用,所以这里转换成引用
  • 相关阅读:
    Jenkins动态部署方案
    01-Java学习笔记
    Tcp实现简单的大小写转换功能
    JavaScript 执行环境 与 变量对象
    JQuery
    JavaScript模板引擎
    ECMA6
    谷歌控制台
    prototype 与 __proto__
    JavaScript Math
  • 原文地址:https://www.cnblogs.com/diegodu/p/4235565.html
Copyright © 2011-2022 走看看