Object oriented design suggestion

前端 未结 9 2180
余生分开走
余生分开走 2021-02-13 04:43

Here is my code:

class Soldier {
public:
   Soldier(const string &name, const Gun &gun);
   string getName();
private:
   Gun gun;
   string name;
};

cl         


        
9条回答
  •  灰色年华
    2021-02-13 05:33

    I would say go with your second option:

    soldier.loadGun(15); // calls Gun.load()
    soldier.fire(); // calls Gun.fire()
    

    Initially it's more work, but as the system gets more complex, you may find that a soldier will want to do other things before and after firing their gun (maybe check if they have enough ammo and then scream "Die suckers!!" before firing, and mutter "that's gotta hurt" after, and check to see if they need a reload). It also hides from the users of the Soldier class the unnecessary details of how exactly the gun is being fired.

提交回复
热议问题