我有一个函数,它获取指向超类的指针并对其执行操作.但是,在某些时候,该函数必须对输入的对象进行深度复制.有什么方法可以执行这样的副本吗?
我想到让函数成为模板函数并让用户传递类型,但我希望C++提供更优雅的解决方案.
#include<iostream>
using namespace std;
class Something
{
public:
int j;
Something():j(20) {cout<<"Something initialized. j="<<j<<endl;}
};
class Base
{
private:
Base(const Base&) {}
public:
Base() {}
virtual Base *clone() { return new Base(*this); }
virtual void ID() { cout<<"BASE"<<endl; }
};
class Derived : public Base
{
private:
int id;
Something *s;
Derived(const Derived&) {}
public:
Derived():id(10) {cout<<"Called constructor and allocated id"<<endl;s=new Something();}
~Derived() {delete s;}
virtual Base *clone() { return new Derived(*this); }
virtual void ID() { cout<<"DERIVED id="<<id<<endl; } …Run Code Online (Sandbox Code Playgroud)