Object oriented design suggestion

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

    If you expose gun, you allow things beyond the member functions of the Gun, which is probably not a good idea:

    soldier.gun = anotherGun; // where did you drop your old gun?
    

    If you use getGun(), the calls look a little ugly, but you can add functions to Gun without modifying Soldier.

    If you encapsulate the functions (which I recommend) you can modify the Gun or introduce other (derived) classes of Gun without changing the interface to Soldier.

提交回复
热议问题