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

标签 c++ object types 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();

我现在希望 cFoo 类型,而 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/

相关文章:

c++ - 错误没有合适的默认构造函数可用

javascript - 将对象转换为数组并省略键

jQuery AJAX : dataType vs mimeType

perl - 如何更改属性类型? (珀尔哞)

c++ - 在 VC++ 中调试时幕后发生了什么

javascript - 从两个数组的内容创建对象

c++ - 为什么 std::unique_ptr 没有 const get 方法?

c++ - 正确设置基类和派生类之间的函数返回

c++ - [ ] - 运算符中的加法和增量表达式

c++ - 将 "value type"作为默认的第二个参数传递给模板