Object oriented design suggestion

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

    Provide a "getGun()" or simply "gun()".

    Imagine one day you may need to make that method more complex:

    Gun* getGun() {
      if (!out_of_bullets_) {
        return &gun_;
      } else {
        PullPieceFromAnkle();
        return &secret_gun_;
      }
    }
    

    Also, you may want to provide a const accessor so people can use a const gun on a const soldier:

    const Gun &getGun() const { return gun_; }
    

提交回复
热议问题