通过getter和setter(accessor)函数访问私有变量的意义是什么? [英] Whats the point of accessing private variables through getter and setter (accessor) functions?

查看:167
本文介绍了通过getter和setter(accessor)函数访问私有变量的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类中,变量通常被私有为封装,并将变量限制在一定范围允许更好的错误控制和更少的错误。这是有道理的,因为变量可访问的位置越少,该变量可能出现的错误就越少。

In classes, variables are often made private for encapsulation, and to limit the variables to a certain scope allow better error control and fewer bugs. This makes sense, as the fewer places a variable can be accessed the fewer places a bug can occur with that variable.

但是,我总是看到变量是私有的,然后一个getter和setter函数,用于检索该值(有时甚至是指向该变量的指针!)。例如 int a 是私有的,以防止公共访问,但 getA() setA ()允许直接访问它们。

However, I always see variables made private, and then a getter and setter function used to retrieve that value (sometimes even a pointer to that variable!). For example int a is private to prevent public access, but then getA() and setA() allow direct access to them.

因此,不要getter函数和setter函数我的意思是具有访问器函数的私有变量与公共变量相同,只有访问它们的代码改变。 (object.variable vs object.getVariable())

So don't getter functions and setter functions defy the point of it being private? I mean private variables with accessor function are the same as public variables, only the code to access them changes. (object.variable vs object.getVariable())

有人会使变量与访问器函数私有吗?

Is there a reason people make variables private with accessor functions? Are there any advantages when compared to making it public?

我一般说的是编程,但大多是C语言(即C,C ++,C#,Obj-C )。

I am talking about programming in general, but mostly in C languages (i.e. C, C++, C#, Obj-C).

推荐答案

这里的关键词和标签是encapsulation。您隐藏了 a 的详细信息,但仍然可以使用。我喜欢已经列出的原因,还有更多。这里是另一个,你正在调试,你发现 a 有一个不正确的值。如果 a 是公开的,则必须检查每个地方是否被访问。如果 a 是一个setter方法的私有,你知道 a code> setA() - 将是放置断点的好地方;)

The key word and tag here is "encapsulation". You're hiding the details of a, while still making it usable. I like the reasons already listed, there are many more. Here's another, you're debugging, and you find a has an incorrect value. If a is public, you'd have to check every place a is accessed. If a is private with a setter method, you know the only place a could have changed is in a call to setA() - would be a great place to put a breakpoint ;)

这篇关于通过getter和setter(accessor)函数访问私有变量的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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