什么是getter和setter方法的使用? [英] what is the use of getter and setter method?

查看:255
本文介绍了什么是getter和setter方法的使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么要使用getters和setter?







有谁能告诉我getter / setter方法的用法是什么?




一个简单的类...所以,我写的类如下所示:



  class X 
{
int i;
public:

void set(int ii){i = ii;}
int get(){return i;}
};

现在,问题是这样的:



< blockquote>


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方法的使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆