人们为什么编写返回非常量引用的私有字段获取器? [英] Why do people write private-field getters returning a non-const reference?

查看:109
本文介绍了人们为什么编写返回非常量引用的私有字段获取器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都可以同意公共变量不利于封装等等。但是,我注意到有很多代码可以执行此类操作:

  class foo {
private:
int integer_;
字符串someString_;
//其他变量
public:
int& integer(){return integer_; }
string& someString(){return someString_; }
//其他函数
}

int main(){
foo f;
f.integer()= 10;
f.someString()=东西;
返回0;
}

我已经看到它在很多地方都在使用,我不知道为什么。基本上,它返回对数据的引用,从而将其直接暴露给外部。所以封装并没有真正实现,从任何角度都没有。



为什么通常使用这种封装?

方案

有一个反复出现的口头禅,即应该使用 getter / setter 函数封装数据。因此,许多(没有经验的或咖啡超负荷的)程序员都会想到他们应该使用类似的东西:

  int& integer(){return integer_; } 

,但这与简单编写没有太大区别:

  class foo {
public://<<<
int integer_;
字符串someString_;
// ...
};

嗯,它添加了一个函数调用,但是您无法控制客户端对引用的操作。 / p>




如果您真的想提供 getter 函数,请输入:

  const int& integer()const {return integer_; } 

相应的 setter 函数如下:

  void整数(const int& value){
integer_ = value;
}


We can all agree on public variables being bad for encapsulation and all that. However, I noticed a lot of code that does this type of stuff:

class foo {
private:
    int integer_;
    string someString_;
    // other variables
public:
    int& integer() { return integer_; }
    string& someString() { return someString_; }
    // other "functions"
}

int main() {
    foo f;
    f.integer() = 10;
    f.someString() = "something";
    return 0;
}

I have seen this being used in many places and I don't get why. Basically it returns a reference to the data and thus exposes it directly to the outside. So encapsulation is not really achieved, not from any perspective.

Why is this commonly used?

解决方案

There's a recurring mantra, that getter/setter functions should be used to encapsulate your data. Hence many (unexperienced or coffee-overloaded) programmers get the idea they should use something like:

int& integer() { return integer_; }

but that isn't much different from simply writing:

class foo {
public: // <<<
    int integer_;
    string someString_;
    // ...
};

Well, it adds a function call, but you cannot control what the client does with the reference.


If you really want to provide a getter function write:

const int& integer() const { return integer_; }

A corresponding setter function looks like:

void integer(const int& value) {
    integer_ = value;
}

这篇关于人们为什么编写返回非常量引用的私有字段获取器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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