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

前端 未结 8 712
挽巷
挽巷 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条回答
  •  猫巷女王i
    2021-01-18 19:13

    get/set should only be necessary when there is some sort of invariant, precondition or postcondition that must be upheld by the class. If the modification of the value doesn't have a 'ripple effect' throughout the rest of the class then the user should be able to modify it directly. However if changing the value will cause something else to happen (e.g., changing a cache size might cause cached items to be purged) then get/set is appropriate.

提交回复
热议问题