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

前端 未结 8 708
挽巷
挽巷 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:03

    I know it is close to herecy, but I hate get/set methods. Loathe them. Almost never write them.

    Generally, a class should either provide much more high-level operations than directly and simply reading and modifying internal state variables, or it should get out of the way and act like the struct it is.

    Even if I were to write one, I would almost never use it inside the class. The whole point of them is that you can change the internal representation of thing without affecting a client. Inside the class, it is the internal representation you care about! If you are tempted to do a lot of operations on the class using its own interface inside the class, you probably have a second class in there fighting to get out.

提交回复
热议问题