在 C++ 中创建未知派生类的实例
假设我有一个指向某个基类的指针,并且我想创建该对象的派生类的新实例。我该怎么做?
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
克隆
这是一个非常典型的模式。
创建新对象
虽然我不认为这是典型的事情;在我看来,它有点代码味道。您确定需要它吗?
Cloning
This is a pretty typical pattern.
Creating new objects
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?
它称为
clone
,您可以实现一个虚拟函数,该函数返回一个指向动态分配的对象副本的指针。It's called
clone
and you implement a virtual function that returns a pointer to a dynamically-allocated copy of the object.