返回对私有成员与公共成员的引用 [英] returning reference to private vs public member

查看:71
本文介绍了返回对私有成员与公共成员的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道提供返回引用而不是将成员公开的公共访问方法的原因可能是什么.QPoint 有方法 int&rxint&ry 让我直接操纵坐标.

I would like to know what could be reasons to provide a public access method returning a reference instead of making the member public. QPoint has methods int& rxand int& ry that let me directly manipulate the coordinates.

我想实现看起来与此类似:

I guess the implentation looks similar to this:

public:
    int& rx(){return x;}
private:
    int x;

到目前为止我唯一的想法是:通过保持成员私有并仅"提供引用,类仍然可以更改为使用不同的数据类型作为其坐标,同时仍然以某种方式"返回引用到一个整数.然而,这个以某种方式"总是需要一个 int 成员.一旦引用泄露,该成员实际上无法再更改.所以这不能成为原因.

The only idea I had so far is the following: By keeping the member private and "only" providing a reference, the class can still change to use a different data type for its coordinates and while still "somehow" returning a reference to an int. However, this "somehow" would always need an int member. Once the reference leaked, the member pratically cannot change anymore. So this cannot be the reason.

在一个相关问题中,接受的答案建议而是将成员设为公开而不是返回引用.

In a related question the accepted answer suggests to rather make the member public instead of returning the reference.

返回引用而不是公开成员(在一般情况下)有什么好处吗?或者这只是 Qt 特定(QPoint 特定?)设计?

Qt4 中的 QPoint

推荐答案

一般来说,通过引用返回成员与使用公共成员一样破坏了封装,两者都不鼓励.

In general, returning a member by reference breaks as much encapsulation as having a public member, and neither is encouraged.

我想当一个类足够简单(纯旧数据——预计接口和数据都不会改变)时,可以将其所有成员设为公开.返回非 const 引用具有相同的效果.所有封装都被破坏了.

I suppose when a class is sufficiently simple (plain old data-it is anticipated that neither interface, nor data will ever change), one could make all its members public. Returning a non const reference had the same effect. All encapsulation is broken.

关于你的问题,没有任何好处.

With respect to your question, there is no benefit.

除了我的回答之外,在这里

这篇关于返回对私有成员与公共成员的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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