这两个类是否违反封装? [英] Do these two classes violate encapsulation?

查看:116
本文介绍了这两个类是否违反封装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class X 
{
protected:
void protectedFunction(){cout< 我受到保护; }
};

class Y:public X
{
public:
using X :: protectedFunction;
};

int main()
{
Y y1;
y1.protectedFunction();
}

这样我就可以暴露基类的一个函数。


  1. 这不违反封装原则吗?

  2. 这是标准的吗?

  3. 这是否有任何用途,或者是否会在新标准中进行更改?

是的,这就是为什么保护已经收到了公正的批评分享。



C ++的创造者Bjarne Stroustrup在他出色的书C ++的设计与进化中感到遗憾:


我对保护的一个关注是
,正是它使它太容易了
使用一个公共基础的方式,可能
sloppily使用全局数据....在
retrospect中,我认为protected是
a的情况下,好论据和
时尚克服了我更好的判断
和我的经验法则接受
的新功能。



class X
{
protected:
    void protectedFunction() { cout << "I am protected" ; }
};

class Y : public X
{
public:
    using X::protectedFunction;
};

int main()
{
    Y y1;
    y1.protectedFunction();
}

This way I am able to expose one of the functions of the base class.

  1. Doesn't this violate the encapsulation principle?
  2. Is there a specific reason as to why this is in standard?
  3. Is there any uses of this, or is it going to be changed in the new standard?
  4. Are there any open issues related to this in the standard?

解决方案

Yes it does and that's why protected has received a fair share of criticism.

Bjarne Stroustrup, the creator of C++, regrets this in his excellent book The Design and Evolution of C++:

One of my concerns about protected is exactly that it makes it too easy to use a common base the way one might sloppily have used global data....In retrospect, I think that protected is a case where "good arguments" and fashion overcame my better judgement and my rules of thumb for accepting new features.

这篇关于这两个类是否违反封装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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