在C ++中创建未知派生类的实例 [英] create instance of unknown derived class in C++

查看:148
本文介绍了在C ++中创建未知派生类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设我有一个指向一些基类的指针,我想创建这个对象的派生类的一个新实例。我如何做到这一点?

let's say I have a pointer to some base class and I want to create a new instance of this object's derived class. How can I do this?

class Base
{
    // virtual
};

class Derived : Base
{
    // ...
};


void someFunction(Base *b)
{
    Base *newInstance = new Derived(); // but here I don't know how I can get the Derived class type from *b
}

void test()
{
    Derived *d = new Derived();
    someFunction(d);
}


推荐答案

克隆



Cloning

struct Base {
   virtual Base* clone() { return new Base(*this); }
};

struct Derived : Base {
   virtual Base* clone() { return new Derived(*this); }
};


void someFunction(Base* b) {
   Base* newInstance = b->clone();
}

int main() {
   Derived* d = new Derived();
   someFunction(d);
}

这是一个非常典型的模式。

This is a pretty typical pattern.

struct Base {
   virtual Base* create_blank() { return new Base; }
};

struct Derived : Base {
   virtual Base* create_blank() { return new Derived; }
};


void someFunction(Base* b) {
   Base* newInstance = b->create_blank();
}

int main() {
   Derived* d = new Derived();
   someFunction(d);
}

虽然我不认为这是一个典型的事情,它看起来像一个代码气味。您确定需要吗?

Though I don't think that this a typical thing to do; it looks to me like a bit of a code smell. Are you sure that you need it?

这篇关于在C ++中创建未知派生类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆