6

This is a question about how to implement some needs I have been having lately. I am sure there is a pattern or common solution for this and, even though I've come with one, I am eager to learn more.

Suppose I am working in a game in which all entities related to the game itself are derived from a class "Actor" (say "obstacle", "moving obstacle", "projectile" and "cannon"). In game, all those entities are stored in a std::vector<Actor *> vector so they can be traversed.

Now, let's suppose each "Actor" can "do" something at each turn and let's give them a method "act". Obstacle::act would do little, Moving_obstacle::act and Projectile::act would move them around and "Cannon::act" would create a new projectile. It sort of makes sense to have a pure virtual function Actor::act so I can in turn do something like:

std::vector<Actor *>::iterator b=myvectorofactors.begin(), e=myvectorofactors.end();
while(b < e)
{
    *b->act();
     b++;
}

And have them all "acting". Well, so far so good... The thing is, Cannon::act could have a different prototype or return value (for example, to store a generated projectile and leter have it pushed into the vector) and this one "small" difference breaks it all.

Now, I know that from certain standpoint these method overloads are completely different functions each. I also know that one can always plan in advance and engineer through the problem with enough foresight... Or one can just manuever around the problem.

In this case at hand, I just used different unique identificators for each derived Actor class and used them to cast to the correspondent class and do the work around them. I am sure I will come around the same problem again and I am curious to know about some entry level solutions.

Thanks in advance for your time.

4

2 回答 2

3

开始是好的,你在这里脱轨:

问题是,Cannon::act 可能有不同的原型或返回值(例如,存储生成的射弹并让其推入矢量)

为什么会呢?行为就是行为。实例必须在没有其他任何东西的情况下弄清楚它。在行动之前,你应该在 ctor 或其他呼叫中训练它。或者它应该在法案调用期间环顾四周。

考虑一下:即使您神奇地准备好不同参数的有效负载,在引用时如何计算出来?调用是抽象的。即使你被一些dynamic_cast感染了,仍然留下哪个cannon应该得到哪个params的问题?

不,主体必须相互合作,或者使用某种消息传递系统(参见调度程序)...

于 2013-06-12T15:37:40.750 回答
1

每个动作的主体不同的内部变量,它们可以使用内部私有拥有/或继承的变量,所以如果你可以在调用动作之前设置这些变量,那么你不需要通过参数发送任何东西以确保安全, 或不出现并发症

于 2013-06-12T15:32:07.823 回答