使用抽象类作为模板类型 [英] Using abstract class as a template type

查看:161
本文介绍了使用抽象类作为模板类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是c ++的新手(来自java)。
我有一个类型 Actor 的stl列表。当 Actor 仅包含真实方法时,没有问题。我现在想要将这个类扩展到几个类,并且需要将一些方法改为抽象,因为它们不再具体了。

I'm still pretty new to c++ (coming over from java). I have a stl list of type Actor. When Actor only contained "real" methods there was no problem. I now want to extend this class to several classes, and have a need to change some methods to be abstract, since they don't make sense as concrete anymore.

As我期望(从文档中)这是坏消息,因为你不能再实例化 Actor ,所以当我遍历我的列表时,我遇到了问题。

As I expected (from the documentation) this is bad news because you can no longer instantiate Actor, and so when I iterate through my list I run into problems.

c ++的方法是什么?

What is the c++ way to do this?

对不起,如果有什么不清楚的话

Sorry if there's anything unclear

推荐答案

你不能直接处理这个问题:

You can not handle this directly:

正如你所看到的那样,当抽象类是抽象的时候,你无法实现对象。

即使是不抽象的类,由于切片问题,也无法将派生对象放入列表中。

解决方案是使用指针。

As you can see when the class is abstract you can not instanciate the object.
Even if the class where not abstract you would not be able to put derived objects into the list because of the slicing problem.
The solution is to use pointers.

所以第一个问题是谁拥有指针(所有者在其生命时间结束时删除它的责任)。

So the first question is who owns the pointer (it is the responcability of the owner to delete it when its life time is over).

使用std :: list<> t他列表通过创建对象的副本并取得副本的所有权来获得所有权。但是指针的析构函数什么也没做。您需要手动调用指针上的删除以获取要激活的obejct的析构函数。所以当std :: list<>在需要获得所有权时保持指针不是一个好的选择。

With a std::list<> the list took ownership by creating a copy of the object and taking ownership of the copy. But the destructor of a pointer does nothing. You need to manually call the delete on a pointer to get the destructor of the obejct to activate. So std::list<> is not a good option for holding pointers when it also needs to take ownership.

// Objects are owned by the scope, the list just holds apointer.
ActorD1   a1; Actor D1 derived from Actor
ActorD2   a2;
ActorD2   a3;

std::list<Actor*>  actorList;
actorList.push_back(&a1);
actorList.push_back(&a2);
actorList.push_back(&a3);

这个工作正常,因为列表超出范围然后对象一切正常。但这对动态(运行时)创建的对象不是很有用。

This works fine as the list will go out of scope then the objects everything works fine. But this is not very useful for dynamically (run-time) created objects.

提升提供了一组处理指针的容器。你给出了容器指针的所有权,当容器超出范围时,容器会破坏对象。

Boost provides a set of containers that handle pointers. You give ownership of the pointer to the container and the object is destroyed by the containter when the container goes out ofd scope.

boost::ptr_list<Actor>  actorList;

actorList.push_back(new ActorD1);
actorList.push_back(new ActorD2);
actorList.push_back(new ActorD2);

这篇关于使用抽象类作为模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆