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

Ben*_*Ben 5 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);
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 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);
}
Run Code Online (Sandbox Code Playgroud)

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


创建新对象

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

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


Pup*_*ppy 6

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