Object oriented design suggestion

前端 未结 9 2203
余生分开走
余生分开走 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:34

    First off, you'd be violating the Law of Demeter by accessing the Gun from outside the Soldier class.

    I would consider methods like these instead:

    soldier.ArmWeapon(...);
    soldier.Attack(...);
    

    This way you could also implement your fist, knife, grenade, baseball bat, laser cat, etc.

提交回复
热议问题