C ++通过调用基类优雅地克隆派生类 [英] C++ elegantly clone derived class by calling base class
问题描述
我需要克隆一个派生类,只给出一个引用或指向基类的指针。下面的代码做的工作,但似乎不优雅,因为我把样板代码到许多派生类C,D,E是兄弟的B(未显示),只是调用每个的默认副本构造函数。是不是默认的复制构造函数是为了,如果只有它可以是虚拟?
I have a need to clone a derived class given only a reference or pointer to the base class. The following code does the job, but doesn't seem elegant, because I'm putting boilerplate code into many derived classes C, D, E that are siblings of B (not shown) that just calls the default copy constructor of each. Isn't that what the default copy constructor is for, if only it could be virtual?
有更好的方法吗?
创建虚拟赋值运算符是错误的,因为我不想让C赋值给B,B到D等,只需克隆B,C,D或E。
Making a virtual assignment operator would be wrong, as I don't want C to assign to B, B to D, etc, just clone B, C, D or E.
#include <iostream>
using namespace std;
class A {
public:
virtual ~A() {}
virtual A* clone()=0;
};
class B : public A {
int i;
public:
virtual A* clone() {
cout << "cloned B" << endl;
return new B(*this);
}
virtual ~B() { cout << "destroyed b" << endl; }
};
int main() {
A* a = new B();
A* aa = a->clone();
delete a;
delete aa;
return 0;
}
推荐答案
克隆逻辑到层次结构中间的自己的类中:
You could always stick all the cloning logic into its own class in the middle of the hierarchy:
template <class Derived, class Base>
class CloneCRTP : public Base {
public:
Derived* clone() const override {
return new Derived(static_cast<Derived const&>(*this));
}
};
然后:
class B : public CloneCRTP<B, A>
{
int i;
public:
virtual ~B() { cout << "destroyed b" << endl; }
};
没有更多的样板。
这篇关于C ++通过调用基类优雅地克隆派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!