C++:结构可以从类继承吗?

2021-12-23 00:00:00 class inheritance struct c++

我正在查看我正在使用的 API 的实现.

I am looking at the implementation of an API that I am using.

我注意到一个结构继承自一个类,我停下来思考它......

I noticed that a struct is inheriting from a class and I paused to ponder on it...

首先,我在学习的 C++ 手册中没有看到一个结构可以从另一个结构继承:

First, I didn't see in the C++ manual I studied with that a struct could inherit from another struct:

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

我猜在这种情况下,结构 B 继承自结构 A 中的所有数据.我们可以在结构中声明公共/私有成员吗?

I guess that in such a case, struct B inherits from all the data in stuct A. Can we declare public/private members in a struct?

但我注意到了这一点:

 class A {};
 struct B : public A {};  

来自我的在线 C++ 手册:

From my online C++ manual:

类是数据结构的扩展概念:它不仅可以保存数据,还可以保存数据和函数.
A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.

即使类A有一些成员函数,上面的继承是否有效?当结构继承它们时,函数会发生什么?反过来呢:从结构继承的类?

Is the above inheritance valid even if class A has some member functions? What happen to the functions when a struct inherit them? And what about the reverse: a class inheriting from a struct?

实际上,我有这个:

struct user_messages {
  std::list<std::string> messages;
};

我曾经像这样在 user_messages.messages 中的 foreach 消息 中迭代它.

And I used to iterate over it like this foreach message in user_messages.messages.

如果我想将成员函数添加到我的结构中,我是否可以更改它的声明并将其提升"为一个类,添加函数,然后仍然像以前一样迭代我的 user_messages.messages?

If I want to add member functions to my struct, can I change its declaration and "promote" it to a class, add functions, and still iterate over my user_messages.messages as I did before?

显然,我仍然是一个新手,我仍然不清楚结构和类如何相互交互,两者之间的实际区别是什么,继承规则是什么......

Obviously, I am still a newbie and I am still unclear how structs and classes interact with each other, what's the practical difference between the two, and what the inheritance rules are...

推荐答案

是的,struct可以从C++中的class继承.

在 C++ 中,类和结构是相同的,除了它们的默认行为关于成员的继承和访问级别.

In C++, classes and struct are the same except for their default behaviour with regards to inheritance and access levels of members.

  • 默认继承 = 私有
  • 成员变量和函数的默认访问级别 = private
  • 默认继承 = public
  • 成员变量和函数的默认访问级别 = public

相关文章