在C ++中创建未知派生类的实例

时间:2011-07-08 14:48:50

标签: c++ derived-class

假设我有一个指向某个基类的指针,我想创建一个这个对象的派生类的新实例。我怎么能这样做?

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);
}

2 个答案:

答案 0 :(得分:14)

克隆

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);
}

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


创建新对象

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);
}

虽然我不认为这是一件典型的事情;它看起来像是一些代码味道。你确定你需要吗?

答案 1 :(得分:6)

它被称为clone并且您实现了一个虚函数,该函数返回指向动态分配的对象副本的指针。