简体   繁体   English

具有私有访问说明符的c ++派生类

[英]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. 接受AB作为参数。 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.

相关问题 C ++:创建可以访问基类私有变量的派生类吗? - C++: Creating derived class that has access to private variables of base? C ++将私有成员从派生类访问到另一个派生类(两者都具有相同的基类) - C++ Access private member from a derived class to another derived class (both have the same base class) C ++类访问说明符详细程度 - C++ Class Access Specifier Verbosity C ++如何创建创建派生类对象的基类,并访问基类的私有成员? - C++ How to create base class which creates derived class object, and access private members of base class? C ++中的Access Specifier - Access Specifier in C++ 调用派生类的虚拟函数时获得访问说明错误,该派生类在基类中是私有的 - Getting access-specifier error while calling virtual function of derived class which is private in base class 从基类继承的C ++公共方法无法访问派生类中的私有成员变量 - C++ public method inherited from base class can not access private member variable in derived class C++ 代码不能使用派生的 class 访问 class 的私有成员 - C++ code that cannot access private members of a class using derived class 如何在没有朋友或C ++的'getter'函数的情况下从派生类访问抽象私有数据? - How do I access abstract private data from derived class without friend or 'getter' functions in C++? C ++允许好友的派生类访问私有嵌套类 - C++ allow derived classes of friend to have access to private nested class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM