区别“默认"的理由.基类的访问说明符 [英] Rationale for difference in "default" access-specifier for a base class

查看:144
本文介绍了区别“默认"的理由.基类的访问说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C ++中structclass之间几乎没有区别.我也了解一些差异的原因.像这样的人,

I know that there're few differences between struct and class in C++. I also understand the reason(s) for few of the difference(s). Like this one,

  • struct的成员由公开 默认;班上的成员是 默认为私有. struct成员默认为 public 的原因是使C++-structC-struct兼容.而且,类成员默认情况下为私有的原因是要引入数据封装的概念(即,实施面向对象的原理/技术/等).
  • Members of struct are public by default; members of class are private by default. The reason why members of struct are public by default, is to make C++-struct compatible with C-struct. And the reason why member of class are private by default, is to introduce the concept of data encapsulation (i.e enforcing object-oriented principles/techniques/etc).

我不明白的是,引用标准$ 11.2/2 [class.access.base]

What I don't understand is this, quoting the Standard $11.2/2 [class.access.base]

在没有访问说明的情况下 基类,当以下情况被假定为公共 派生类被声明为struct 当班级被假定为私人时 被声明为class.

In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

这种扭曲和反统一的理由是什么? 为什么需要这种区别?

What is the rationale for this twist and anti-uniformity? Why is this difference needed?

标准示例,

class B {  };
class D1 : private B {  };
class D2 : public B { };
class D3 : B { };         //B private by default
struct D4 : public B { };
struct D5 : private B { };
struct D6 : B { };        //B public by default
class D7 : protected B { };
struct D8 : protected B { };

这里B是D2,D4和D2的公共基地 D6,D1,D3和D5的私有基地, 以及D7和D8的受保护基地.

Here B is a public base of D2, D4, and D6, a private base of D1, D3, and D5, and a protected base of D7 and D8.


编辑

您可能会说,鉴于struct和class的默认访问权限不同(这种区别在上面的要点中给出),这种区别是有道理的.但是我认为inherited-struct完全与C-struct(不支持继承)不兼容,无论您如何获取它.我可能是错的.这就是为什么我在寻求很好的解释(可能带有示例)的原因! :-)


EDIT

Some of you might say, this difference makes sense given the default access for struct and class being different (the difference given in the bullet-point above). But I think, inherited-struct altogether is incompatible with C-struct (which doesn't support inheritance), no matter how you derive it. I may be wrong though. That is why I'm seeking good explanations, possibly with examples! :-)

推荐答案

我不确定您为什么认为这是一个扭曲,您与成员子对象和基类子对象是否具有一致性.对于用struct声明的类,它们都是公共的;对于用class声明的类,它们都是私有的.简单易记.

I'm not sure why you think it's a twist, you have consistency with member sub-objects and base class sub-objects. They are both public for classes declared with struct and private for classes declared with class. Simple and easy to remember.

这篇关于区别“默认"的理由.基类的访问说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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