什么是getter和setter方法的使用?

编程入门 行业动态 更新时间:2024-10-25 15:28:57
本文介绍了什么是getter和setter方法的使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 为什么要使用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方法的使用?

本文发布于:2023-05-27 09:57:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285757.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file 'D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!