具有混合继承修饰符的钻石继承(受保护/私有/公共)

发布于 2024-12-28 12:32:56 字数 960 浏览 0 评论 0原文

假设我们有类 A,B,C,D,其中 A 是基础,B,C 是介于两者之间,D 是在钻石模型中派生的。

注意

B 类私有模式下虚拟继承A 类

C 类继承保护模式下的 virtualy A 类

class A
{
public:
    int member;  // note this member
};
class B :
    virtual private A // note private 
{

};
class C :
    virtual protected A // note protected
{

};
class D :
    public B, // doesn't metter public or whatever here
    public C
{

};

int main()
{
    D test;
    test.member = 0; // WHAT IS member? protected or private member?
    cin.ignore();
    return 0;
}

现在,当我们创建class D 的实例时,成员会是什么?私人的还是受保护的哈哈?

图 2:

如果我们这样做会怎样:

class B :
    virtual public A // note public this time!
{

};
class C :
    virtual protected A // same as before
{

};

我想 member 在第二个示例中将是公开的,不是吗?

let's say we have class A,B,C,D where A is base, B,C are between and D is derived in diamond model.

NOTE:

class B inherits virtualy class A in private mode,

class C inherita virtualy class A in protected mode.

class A
{
public:
    int member;  // note this member
};
class B :
    virtual private A // note private 
{

};
class C :
    virtual protected A // note protected
{

};
class D :
    public B, // doesn't metter public or whatever here
    public C
{

};

int main()
{
    D test;
    test.member = 0; // WHAT IS member? protected or private member?
    cin.ignore();
    return 0;
}

now when we make an instance of class D what will member be then? private or protected lol?

Figure No2:

what if we make it so:

class B :
    virtual public A // note public this time!
{

};
class C :
    virtual protected A // same as before
{

};

I suppose member will be public in this second example isn it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半衾梦 2025-01-04 12:32:56

§11.6 多路访问 [class.paths]

如果可以通过多重继承图通过多个路径访问某个名称,则访问权限是提供最多访问权限的路径的访问权限。 [示例:

class W { public: void f(); };
A 类:私有虚拟 W { };
B 类:公共虚拟 W { };
C 类:公共 A,公共 B {
   无效 f() { W::f(); } // 好的
};

由于 W::f() 可沿公共路径通过 BC::f() 使用,因此允许访问。 —结束示例]

我认为我不需要添加任何其他内容,但另请参阅此缺陷报告(已关闭为“不是缺陷”)。

§11.6 Multiple access [class.paths]

If a name can be reached by several paths through a multiple inheritance graph, the access is that of the path that gives most access. [ Example:

class W { public: void f(); };
class A : private virtual W { };
class B : public virtual W { };
class C : public A, public B {
   void f() { W::f(); } // OK
};

Since W::f() is available to C::f() along the public path through B, access is allowed. —end example ]

I think I don't need to add anything else, but see also this defect report (which was closed as "not a defect").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文