[英]c++ derived class with private access specifier
I have a derived class (class B) from a base class (class A). 我有一个从基类(类A)派生的类(类B)。 Class A has a protected virtual function foo() which I want to override and use it as private in derived class.
类A具有受保护的虚函数foo(),我想重写它并将其用作派生类中的私有函数。
Class A{
protected:
virtual void foo() = 0;
}
I am wondering whether the following 我想知道以下情况
Class B: public Class A
private:
virtual void foo();
and 和
Class B: private Class A
private:
virtual void foo();
are the same. 是相同的。
They are not the same. 她们不一样。 In the first example,
B
is-an - A
, in the second it isn't. 在第一个示例中,
B
是-an - A
,在第二个示例中不是。 So in the first case you can have code such as 因此,在第一种情况下,您可以使用如下代码
void foo(const A& a);
which accepts A
and B
as arguments. 接受
A
和B
作为参数。 With private inheritance, you could not do that. 使用私有继承,您将无法做到这一点。 For example,
例如,
A a;
B b;
foo(a); // OK with private and public inheritance
foo(b); // OK only with public inheritance, i.e. B is an A.
No, your two cases are not the same. 不,您的两种情况不一样。
In the second case class B
can't be casted to class A
, because a private base class is hidden. 在第二种情况下,无法将
class B
强制转换为class A
,因为私有基类被隐藏了。 in this aspect would get the same behavior as if class A
would be a member of class B
. 在这方面,将获得与
class A
将成为class B
的成员相同的行为。
两者都不相同在公共继承类A中,foo()将被保护为类B中的成员。在私有继承中,类B仅可以访问类A的公共成员,因此在类B中将不会出现任何类A的foo()。 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.