gpt4 book ai didi

c++ - 具有混合继承修饰符的菱形继承(钻石问题)( protected /私有(private)/公共(public))

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:49 27 4
gpt4 key购买 nike

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

注意:

class Bprivate 模式下继承virtualy class A

C 类保护 模式下继承虚拟 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 的实例时,member 会是什么?私有(private)或 protected 哈哈?

图 2:

如果我们这样做会怎样:

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

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

};

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

最佳答案

§11.6 多路访问 [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 ]

我想我不需要添加任何其他内容,但另请参阅 this defect report (被关闭为“不是缺陷”)。

关于c++ - 具有混合继承修饰符的菱形继承(钻石问题)( protected /私有(private)/公共(public)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8957187/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com