Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Luc is right on with using the Visitor pattern, I'm just expanding on that by giving an example of how you could do it.</p> <pre><code>#include &lt;iostream&gt; #include &lt;conio.h&gt; using namespace std; class SpaceObject; class SpaceShip; class GiantSpaceShip; class Asteroid; class ExplodingAsteroid; class SpaceObject { public: virtual void CollideWith(SpaceObject*) {} virtual void CollideWith(SpaceShip*) {} virtual void CollideWith(GiantSpaceShip*) {} virtual void CollideWith(Asteroid*) {} virtual void CollideWith(ExplodingAsteroid*) {} }; class Asteroid : public SpaceObject { public: virtual void CollideWith(SpaceObject* o) { o-&gt;CollideWith(this); } virtual void CollideWith(SpaceShip *) { cout &lt;&lt; "Asteroid hit a SpaceShip" &lt;&lt; endl; } virtual void CollideWith(GiantSpaceShip *) { cout &lt;&lt; "Asteroid hit a GiantSpaceShip" &lt;&lt; endl; } }; class ExplodingAsteroid : public Asteroid { public: virtual void CollideWith(SpaceObject* o) { o-&gt;CollideWith(this); } virtual void CollideWith(SpaceShip *) { cout &lt;&lt; "ExplodingAsteroid hit a SpaceShip" &lt;&lt; endl; } virtual void CollideWith(GiantSpaceShip *) { cout &lt;&lt; "ExplodingAsteroid hit a GiantSpaceShip" &lt;&lt; endl; } }; class SpaceShip : public SpaceObject { public: virtual void CollideWith(SpaceObject* o) { o-&gt;CollideWith(this); } virtual void CollideWith(Asteroid* o) { o-&gt;Asteroid::CollideWith(this); } virtual void CollideWith(ExplodingAsteroid* o) { o-&gt;ExplodingAsteroid::CollideWith(this); } }; class GiantSpaceShip : public SpaceShip { public: virtual void CollideWith(SpaceObject* o) { o-&gt;CollideWith(this); } virtual void CollideWith(Asteroid* o) { o-&gt;Asteroid::CollideWith(this); } virtual void CollideWith(ExplodingAsteroid* o) { o-&gt;ExplodingAsteroid::CollideWith(this); } }; int main() { SpaceObject* s = new GiantSpaceShip(); SpaceObject* a = new ExplodingAsteroid(); a-&gt;CollideWith(s); getch(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload