复制抽象基类的子类
我有一个抽象基类来强制某些子类重载 <<操作员。
我将一堆指向这些子类实例的指针存储在 std::stack 中...有时我希望复制堆栈的顶部项目(并将其推到顶部)。
问题是,我无法实例化抽象类。显然,因为我想为每个子类执行此操作,所以我不知道类型...
我想知道这是否可能在不添加另一个纯虚拟方法(例如“Base *clone() = 0”)的情况下实现在我的每个子类中实现它?当然必须有一种更清洁的方法。
I have an abstract base-class to enforce some subclasses to overload the << operator.
I am storing a bunch of pointers to instances of these subclasses in an std::stack... At some point I wish to duplicate the top item of the stack (and push it on top).
The problem is, I cannot instantiate an abstract class. And obviously since I want to do this for each of my subclasses, I won't know the type...
I wonder if this is even possible without adding another pure virtual method (say 'Base *clone() = 0') and implement it in each of my subclasses? Surely there must be a cleaner way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为在这种情况下您实际上需要一个
Clone
方法。您希望在运行时动态复制子类项,而在运行时更改行为的正常方法是虚拟方法。如果不使用某种虚拟方法,您将无法确定它是哪个孩子。不过,您可能可以使用 CRTP 自动为您生成该克隆:I think you actually need a
Clone
method in this case. You want to dynamically copy the subclass item at runtime, and the normal way to change behavior at runtime is virtual methods. Without using some virtual method you would have no way of figuring out which child it is. You could probably use CRTP to automatically generate that Clone for you though:您的意思是制作类的副本,而不是复制指针。
您需要实现自己的打字。换句话说,有一个返回类类型的虚函数,然后创建适当的类
或启用 RTTI(运行时类型信息)来执行相同的操作。因为 RTTI 会影响每个类,所以创建您自己的 typeof 方法可能会更有效。
然后您可以
复制构造函数可能在
switch
psuedocode
DC
Do you mean making a copy of the class, rather than duplicating the pointer.
You will need to either implement your own typing. in other words have a virtual function that returns the class type and then create the appropriate class
Or enable RTTI (Run-Time Type Information) to do the same thing. because RTTI effects every class its possibly more efficient to create your own typeof method.
Then you can
a copy constructor probably in a
switch
psuedocode
DC