嗯,我不确定这个。
我有一个类
class Object { int internalValue ; struct SomeStructType { int superInternalValue ; } someStruct ; public: int getInternalValue() { return internalValue ; } int getSuperInternalValue() { return someStruct.superInternalValue ; } void printThatInternalValue() { // Its seems pretty clear we should just access // the private value directly and not use the public getter printf( "%d", internalValue ) ; } void printThatSuperInternalValue() { // Now here the access pattern is getting more complicated. // Shouldn't we just call the public access function // getSuperInternalValue() instead, even though we are inside the class? printf( "%d", someStruct.superInternalValue ) ; } } ;
因此对于类的内部操作,它可以直接使用 someStruct.superInternalValue
,但使用类的公共(public) getter 函数 getSuperInternalValue()
似乎更干净。
我能看到的唯一缺点是,如果您尝试使用 getter 修改 superInternalValue
会给您一个副本,在这种情况下这显然不是您想要的。但是对于读取访问,是否应该在类内部使用公共(public) getter 函数?
最佳答案
如果访问器不能被覆盖,一个类可以直接使用它的私有(private)成员。否则,它应该使用访问器,这样如果它被覆盖,该类将继续正确运行。
关于language-agnostic - 一个类应该直接使用它的私有(private)成员还是公开暴露的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2293260/