如果我在类成员函数的定义中使用全局变量,会违反封装吗? [英] Is encapsulation violated, if I use a global variable in a class member function's definition?

查看:296
本文介绍了如果我在类成员函数的定义中使用全局变量,会违反封装吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求解释什么是封装,我回答捆绑数据和修改此数据的功能,称为封装。

I've been asked to explain what encapsulation is and I replied "bundling of data and functions that modify this data, is called encapsulation."

答案是紧接着是另一个问题:因此,根据您的定义,如果我从类的成员函数中修改全局变量,则违反了封装。

The answer was followed by another question—"So, by your definition if I modify a global variable from a member function of a class then the encapsulation is violated."

我不确定我的解释是错误的还是下面的问题是否有效以及我对是的回答是否正确。

I am not sure whether my explanation is wrong or following question is valid and my answer to it as YES is correct.

有人可以帮忙。

推荐答案

引用维基百科


在编程语言中,封装用于表示两个与
相关但截然不同的概念之一,有时还用于表示其组合

In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:


  • 一种用于限制对某些对象组件访问的语言机制。

  • 一种语言构造,可促进将数据与操作于其上的方法(或其他功能)捆绑在一起该数据

在我的拙见中,后续问题的答案是主观的,取决于

In my humble opinion the answer to the follow up question is subjective and it depends on the interpretation of the notion of encapsulation.

例如,如果将封装数据限制为类的成员变量,则这并不违反。每个人都可以访问不属于对象的全局变量,因此,通过成员函数访问它并不构成任何封装违规。

For example it's not a violation if the encapsulating data are limited to be the member variables of classes. A global variable that doesn't belong to an object is accessible by everyone and thus, accessing it via a member function doesn't consist any encapsulation violation.

如果您认为应该将封装应用于整个程序,则该全局变量应该已经绑定到一个对象,因此,对其的原始访问会构成封装违规。

On the other hand if you consider that encapsulation should be applied to your entire program then this global variable should have been bundled to an object and thus, raw access to it constitutes an encapsulation violation.

最重要的是,答案在于神学领域,这意味着它取决于不同编程原理如何解释封装。

The bottom line is that the answer lies in the realms of theology, meaning that it depends on how encapsulation is interpreted by the different programming dogmas.

这篇关于如果我在类成员函数的定义中使用全局变量,会违反封装吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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