<分区>
Possible Duplicate:
Why use getters and setters?
Can anyone tell me what is the use of getter/setter method?
在一次采访中有人让我写一个简单的类...所以,我写了如下所示的类:
class X
{
int i;
public:
void set(int ii){ i = ii;}
int get(){ return i;}
};
现在,问题是这样的:
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.
为了反驳我的推理,面试官说......“那么,你为什么要提供一个公共(public)的 getter/setter 方法??因为,这些成员函数是公共(public)的, 所以变量 'i' 仍然暴露给外界,任何人都可以更改 'i' 的值。”
此外, 面试官建议我重写我之前的课如下:
class X
{
public:
int i;
};
好处是:您可以更快地修改“i”的值...因为这次不需要函数调用。
虽然面试官的推理似乎不错……因为通过创建私有(private)变量“i”和公共(public) get/set 方法,您无法保护您的数据。那么,为什么要写 get()/set() 方法呢?