C++中的继承默认访问修饰符

Inheritance default access modifier in C++

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

// A.h
#pragma once

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

具体形式不重要。由于这是一个接口,所以会有一个继承自A的classB。在 class 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 默认是什么?

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

What does class B : A default to?

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

But will forgetting the public keyword affect my project in any sense?

是的。别忘了。

考虑以下因素:

// 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
}