你可以跨类实例访问私有成员变量吗? [英] can you access private member variables across class instances?

查看:112
本文介绍了你可以跨类实例访问私有成员变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为这是可能的,但如果你有两个相同的类的实例,你是否允许从另一个访问其私人成员?

I didn't think it was possible, but if you have two instances of the same class, are you allowed to access one's private members from the other?

这是为什么你也可以在复制构造函数中这样做?其实是复制构造函数的原因是允许的吗?

Is this why you can also do this in copy constructors? in fact, is the copy constructor the reason this is allowed? Doesn't this break encapsulation?

推荐答案

是的,类中的任何代码都可以访问类的任何实例中的私有数据。

Yes, any code within a class can access private data in any instance of the class.

如果您将封装的单位视为对象,这会中断封装。 C ++不会这样想;它认为封装在类中。

This breaks encapsulation if you think of the unit of encapsulation as the object. C++ doesn't think of it that way; it thinks of encapsulation in terms of the class.

这篇关于你可以跨类实例访问私有成员变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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