Calling this->get/this->set methods versus directly accesing member variables in C++

前端 未结 8 683
挽巷
挽巷 2021-01-18 18:21

Suppose I have a class Foo, with a private variable bar_ containing some state for Foo. If necessary, I may write public get/set metho

8条回答
  •  甜味超标
    2021-01-18 19:18

    There is no rule that fits every situation in my opinion. Sometimes, it is better to write these private set/get functions, sometimes it is not.

    For example, if all what get/set functions do is this:

    void set(int n)
    {
       member_n = n;
    }
    int get_n() const
    {
      return member_n;
    }
    

    Then, there is no need actually for these functions!

    In other situations, where you need to normalize a value for example, you could write those get/set functions. e.g. to normalize an angle:

    void setAngle(int angle)
    {
      member_angle = angle%two_PI;
    }
    

提交回复
热议问题