可能重复: 为什么要使用getters和setter?
有谁能告诉我getter / setter方法的用法是什么?
一个简单的类...所以,我写的类如下所示:
class X { int i; public: void set(int ii){i = ii;} int get(){return i;} };现在,问题是这样的:
Q1。为什么你声明变量'i'是私有的而不是公开的?
我的答案: Bcoz,数据总是敏感的,
为了反驳我的推理,面试官说:那么,为什么你提供了一个公共getter / setter方法??因为,这些成员函数是public,所以仍然变量'i'暴露在外界,任何人都可以更改'i'的值。
此外,访问员建议我重写我以前的类如下:
class X { public: int i; };
好处是:你可以更快地修改'i'
面试官的推理似乎很好,虽然....因为通过私有变量'i'和公共get / set方法,你不能保护您的数据。所以,为什么我们写get()/ set()方法?
解决方案并且如果需要(例如有效性检查),具有更复杂逻辑的getter方法。如果你不使用getter / setter,你必须写它们,然后在任何你改变字段的地方改变代码,这可能导致很难找到的错误。
Possible Duplicate: Why use getters and setters?
Can anyone tell me what is the use of getter/setter method?
In one of the interview someone asked me to write a simple class...so, I wrote the class as shown below:
class X { int i; public: void set(int ii){ i = ii;} int get(){ return i;} };Now, The question goes like this:
Q1. Why did you declare the variable 'i' as private and not as public?
My answer: Bcoz, data is always sensitive and by declaring it private you'll prevent it from being exposed to the outside world.
To counter my reasoning, the interviewer said..."Then, why did you provide a public getter/setter method?? Since, these member functions are public, so still variable 'i' is exposed to outside world and anyone can change the value of 'i'."
Further, The interviewer suggested me to re-write my previous class as follows:
class X { public: int i; };
The benefit would be: you can modify the value of 'i' more quickly...since there is no function calling required this time.
The interviewer's reasoning seems good though....because by making private variable 'i' and public get/set method, you cant protect your data. So, Why do we write get()/set() method ?
解决方案The purpose is that you can always change the setter and the getter method with more sophisticated logic, if needed (for example validity check). If you don't use getter/setter you must write them and then change the code everywhere you change the field, which can lead to errors which will be very hard to find.
更多推荐
什么是getter和setter方法的使用?
发布评论