c++ - getter和setter方法有什么用?

标签 c++ getter-setter

<分区>

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() 方法呢?

最佳答案

目的是如果需要(例如有效性检查),您始终可以使用更复杂的逻辑更改 setter 和 getter 方法。如果您不使用 getter/setter,则必须编写它们,然后在更改字段的任何地方更改代码,这可能会导致很难发现的错误。

关于c++ - getter和setter方法有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12098636/

相关文章:

c++ - 如何获取 Pin 中存储指令写入的值?

c++ - 在 C++ 中绑定(bind)多个引用的临时对象的生命周期

c++ - PE 文件格式部分附加

java - 如何从 getter/setter 中删除逻辑?

java - 使用字符串作为参数的问题

php - 永久设置私有(private)类变量 PHP

C++ 文件需要库支持

c++ - Qt找不到创建的目录

java - 如何累积一个调用 setter 方法并以其中的变量作为参数?

ios - 无法在 Swift 上设置/获取映射对象数组到 userDefaults