继承:如果默认为私有,为什么这两个示例的工作方式不同?

Inheritance: If private is default, why do these two examples not work the same way?

我正在研究 C++ 中的继承。据我所知,如果您不指定,B 将始终从 A 继承 private。

为什么这段代码有效:

struct A {};
struct B : A {};

int main(void)
{
    A b = B();
    return 0;
}

但这会产生“A 是 B 的不可访问的基”错误:

struct A {};
struct B : private A {};

int main(void)
{
    A b = B();
    return 0;
}

我希望它们是一样的吗?

如果派生 class 是使用单词 class 定义的,则默认为私有继承。

如果您使用 struct 创建它,则继承默认为 public。

来自 cppreference:

A class defined with the keyword struct has public access for its members and its base classes by default.

A class defined with the keyword class has private access for its members and its base classes by default.

或来自Derived Classes documentation

If access-specifier is omitted, it defaults to public for classes declared with class-key struct and to private for classes declared with class-key class.

以上引用解释了您的程序的行为。