假设我有一个指向某个基类的指针,我想创建一个这个对象的派生类的新实例。我怎么能这样做?
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);
}
答案 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
并且您实现了一个虚函数,该函数返回指向动态分配的对象副本的指针。