c ++ Object创建相同类型的新实例

Mag*_*eit 2 c++ types object instantiation

有没有办法让对象有可能创建自己类型的新对象,而不指定这种类型?

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();
Run Code Online (Sandbox Code Playgroud)

我现在想c成为类型Foo,而d应该是类型Bar.

Fer*_*yer 5

简答:不,没有办法让这种魔力发生.

您可以使用宏来更轻松地覆盖子类中的函数,或者创建一个使用"奇怪的重复模板模式"的中间类:

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*
Run Code Online (Sandbox Code Playgroud)

但这绝对不值得付出努力.