有没有办法让一个对象有可能创建它自己类型的新对象,而无需指定这种类型?
class Foo {
public:
virtual Foo* new_instance() {
return new type_of(this); // Some magic here
}
};
class Bar: public Foo {
};
Foo* a = new Foo();
Foo* b = new Bar();
Foo* c = a->new_instance();
Foo* d = b->new_instance();
我现在希望 c
是 Foo
类型,而 d
应该是 Bar
类型。
最佳答案
简短回答:不,没有办法让这种魔法发生。
您可以使用宏来更轻松地覆盖子类中的函数,或者创建一个使用“奇怪的重复模板模式”的中间类:
template <typename T>
class FooDerived : public Foo
{
public:
T* new_instance() {
return new T();
}
};
class Bar : public FooDerived<Bar>
{
};
Foo* a = new Bar();
Foo* b = a->new_instance(); // b is of type Bar*
但这肯定不值得付出努力。
关于c++对象创建相同类型的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22997400/