【问题标题】:Inheritance default access modifier in C++C++ 中的继承默认访问修饰符
【发布时间】:2021-06-10 17:19:43
【问题描述】:

我有一个 C++ 接口,看起来像这样:

// A.h
#pragma once

class A
{
public:
    //Some declarations.    
private:    
    //Some declarations.
protected:
    //Some declarations.
};

具体的形式并不重要。由于这是一个接口,所以会有一个类B 继承自A。在B 类的头文件中,我有:

// B.h
#pragma once

class B : A
{
public:
    //Some declarations.    
private:    
    //Some declarations.
protected:
    //Some declarations.
};

我担心的是我倾向于使用class B : A 而不是class B : public A,只是我记性不好。

到目前为止,我对此没有任何问题,因为它是一个足够小的项目。但是忘记public 关键字会在任何意义上影响我的项目吗?

或者更简洁地说,我知道访问修饰符是如何工作的,但是class B : A 默认是什么?

【问题讨论】:

  • 嗨,我已经看过了,它没有解决默认修饰符。
  • 不是吗? class D : private A // 'private' is default for classes
  • 可能已经监督了它,抱歉。谢谢。

标签: c++ inheritance interface access-modifiers modifier


【解决方案1】:

class B : A 默认是什么?

class B : private A { /*...*/ }

但是忘记 public 关键字会影响我的项目吗?

是的。别忘了。

考虑以下几点:

// A.h
class A {

public:
   void f(){}  
};

// B.h
class B : A {};

int main() {

   B b;
   b.f(); // f is inaccessible because of private inheritance
}

【讨论】:

    【解决方案2】:

    structclass 之间的唯一区别在于,在 struct 中,除非另有声明,否则一切都是公开的,而在 class 中,除非另有声明,否则一切都是私有的。这包括继承。所以class B : A默认是私有继承,struct B : A默认是公有继承。

    【讨论】:

    • @rustyx 当然,但在回答问题时没有提及struct 的工作方式相反会产生误导。
    猜你喜欢
    • 2017-01-12
    • 2011-04-10
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2016-01-29
    • 2013-09-27
    • 2012-03-03
    • 2017-08-17
    相关资源
    最近更新 更多