网站中上传资料存放ftp,代写1000字多少钱,wordpress tag无法找到该页,网站建设和管理情况自查报告拷贝一个多态类可能会导致切片问题#xff0c;为了解决这个问题#xff0c;应覆盖一个虚clone函数#xff0c;让他根据实际类型进行复制并返回一个到新对象的所有权的指针#xff08;std::unique_ptr#xff09;,在派生类#xff0c;通过使用所谓的协变返回类型来返回派生…拷贝一个多态类可能会导致切片问题为了解决这个问题应覆盖一个虚clone函数让他根据实际类型进行复制并返回一个到新对象的所有权的指针std::unique_ptr,在派生类通过使用所谓的协变返回类型来返回派生类型。
struct Base
{Base() default;virtual ~Base() default;virtual std::unique_ptrBase Clone(){return std::make_uniqueBase();}virtual string GetName() const { return Base; }protected:Base(const Base) default;Base operator(const Base) default;
};struct Derived :public Base
{Derived() default;std::unique_ptrBase Clone() override{return std::make_uniqueDerived();}virtual string GetName() const { return Derived; }
protected:Derived(const Derived) default;Derived operator(const Derived) default;
};int main()
{auto pBase std::make_uniqueBase();printf(pBasename:%s\n,pBase-GetName().c_str());auto pBase1 pBase-Clone();printf(pBase1name:%s\n, pBase1-GetName().c_str());std::unique_ptrBase pDerived std::make_uniqueDerived();printf(pDerivedname:%s\n, pDerived-GetName().c_str());std::unique_ptrBase pDerived1 pDerived-Clone();printf(pDerivedname:%s\n, pDerived1-GetName().c_str());system(pause);return 0;
}结果