Object oriented design suggestion

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

    There's no golden rule that applies 100% of the time. It's really a judgement call depending on your needs.

    It depends on how much functionality you want to hide/disallow for the gun from access to the Solider.

    If you want to have only read only access to the Gun you could return a const reference to your own member.

    If you want to expose only certain functionality you could make wrapper functions. If you don't want the user to try to change Gun settings through the Soldier then make wrapper functions.

    Generally though, I see the Gun as it's own object and if you don't mind exposing all of Gun's functionality, and don't mind allow things to be changed through the Soldier object, just make it public.

    You probably don't want a copy the gun so if you make a GetGun() method make sure that you aren't returning a copy of the gun.

    If you want to keep your code simple then have the soldier responsible for dealing with the gun. Does your other code need to work with the gun directly? Or can a soldier always know how to work/reload his own gun?

提交回复
热议问题