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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3574040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:09:47  来源:igfitidea点击:

C++: Can a struct inherit from a class?

c++classinheritancestruct

提问by augustin

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

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

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

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

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

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

struct A {};
struct B : public 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?

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

But I noticed this:

但我注意到了这一点:

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

From my online C++ manual:

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

A class is an expanded concept of a data structure: instead of holding only data, it can hold bothdata and functions.
类是一数据结构的一个扩展的概念:不是只持有数据,它可以容纳两个数据和功能。

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?

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

Practically speaking, I have this:

实际上,我有这个:

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

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

我曾经像这样迭代它foreach message in 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?

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

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...

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

回答by Vite Falcon

Yes, struct can inherit from class in C++.

是的,struct 可以从 C++ 中的类继承。

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

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

C++ class

C++类

  • Default Inheritance = private
  • Default Access Level for Member Variables and Functions = private
  • 默认继承 =私有
  • 成员变量和函数的默认访问级别 =私有

C++ struct

C++ 结构体

  • Default Inheritance = public
  • Default Access Level for Member Variables and Functions = public
  • 默认继承 =公共
  • 成员变量和函数的默认访问级别 = public

回答by maxschlepzig

In C++

在 C++ 中

struct A { /* some fields/methods ... */ };

is equivalent to:

相当于:

class A { public: /* some fields/methods ... */ };

And

class A { /* some fields/methods ... */ };

is equivalent to:

相当于:

struct A { private: /* some fields/methods ... */ };

That means that the members of a struct/class are by default public/private.

这意味着结构/类的成员默认是 public/private

Using structalso changes the default inheritanceto public, i.e.

使用struct还将默认继承更改public,即

struct A { }; // or: class A { };
class B : A { };

is equivalent to

相当于

struct A { }; // or: class  A { };
struct B : private A { };

And the other way around, this

反过来,这个

struct A { }; // or: class A { };
struct B : A { };

is equivalent to:

相当于:

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

Summary: Yes, a structcan inherit from a class. The difference between the classand structkeywords is just a change in the default private/public specifiers.

总结:是的,astruct可以继承自一个类。classstruct关键字之间的区别只是默认私有/公共说明符的更改。

回答by Michael Anderson

The only difference between a struct and a class is the default access level for members (private for classes, public for structs). This means that a struct should be able to inherit from a class, and vice-versa.

结构体和类之间的唯一区别是成员的默认访问级别(类是私有的,结构是公共的)。这意味着结构应该能够从类继承,反之亦然。

However, there is usually a difference in how structs and classes are used that is not mandated by the standard. structs are often used for pure data, ( or objects without polymorphism depending on your projects preference) and classes are used for the other cases. I emphasise that this is just a stylistic difference and not required.

但是,标准未强制要求的结构和类的使用方式通常存在差异。结构通常用于纯数据(或没有多态性的对象,具体取决于您的项目偏好),而类用于其他情况。我强调这只是风格上的差异,并不是必需的。

回答by Puppy

The main thing to understand is that structs come from C, whereas classes are C++. This means that although structs ARE first-class object-orientated citizens, they also have a legacy purpose, which is the reason for classes being separate and structs being default-access public. However, once this is done with, they're absolutely and totally identical and interchangable in every way.

要理解的主要事情是结构来自 C,而类是 C++。这意味着虽然结构体是一流的面向对象的公民,但它们也有一个遗留用途,这就是类被分离而结构体是默认访问公共的原因。但是,一旦完成,它们在各个方面都绝对完全相同并且可以互换。

回答by MBennett

A struct is the same thing as a class except that a class defaults its members to private while a struct defaults its members to public. As a result, yes, you can inherit between the two. See in C++, can I derive a class from a struct.

结构与类相同,只是类将其成员默认为私有,而结构将其成员默认为公有。因此,是的,您可以在两者之间进行继承。在 C++ 中看到,我可以从 struct 派生一个类吗

回答by Chubsdad

Yes. Struct can inherit from a class and vice versa. The accessibility rule is

是的。结构可以从类继承,反之亦然。可访问性规则是

$11.2/2- "In the absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class."

$11.2/2-“在没有基类的访问说明符的情况下,当派生类声明为 struct 时假定为 public,而在类声明为 class 时假定为 private。”

EDIT 2: So you can change your class as:. Note that it is a badidea to have public data members usually.

编辑 2:因此您可以将您的课程更改为:。请注意,通常拥有公共数据成员是一个主意。

class user_messages {  // i also changed the name when OP was modified :)
public:   
   std::list<std::string> messages;  
};

回答by Maciej Hehl

Yes a structcan inherit from a class. structand classdiffer only in the access-specifier assumed for the members and for a base classes (or structs) if not specified explicitly in C++ . For structs it's public. For classes it's private.

是的,struct可以从类继承。struct并且class不同之处仅在假定成员接入说明符和用于基类(或结构),如果不是在C中明确指定++。对于结构,它是public. 对于课程,它是private.

The sentence you quote from the manual is about the concept of a class in C++, as compared to the concept of a data structure in C. In C++ new keyword - classwas introduced to better reflect the change in the concept, but for compatibility with code in C, an old keyword structwas left and it's meaning is as described above.

你从手册中引用的那句话是关于C++中类的概念,与C中数据结构的概念相比。在C++class中引入了new关键字-是为了更好地反映概念的变化,但为了与代码兼容在 C 中,struct遗留了一个旧关键字,其含义如上所述。

回答by Tony Delroy

struct and class are pretty much interchangeable - just with different defaults in that classes default to private inheritance and members, structs to public. The class keyword (and not struct) must be used for eg. "template <class T>".

struct 和 class 几乎可以互换 - 只是在该类中具有不同的默认值,默认为私有继承和成员,结构为公共。class 关键字(而不是 struct)必须用于例如。“模板 <class T>”。

That said, many programmers use the two to give a slight suggestion to a programmer reading the code: by using a struct you're subtly suggesting a less encapsulating, OO design. A struct might be used internal to a library - where getting at the guts of it all is fair game, whereas classes are used on the boundary where API changes would inconvenience clients and better abstraction is useful. This very loose convention has grown out of the difference in default accessibility - lazy/efficient/concise (take your pick) programmers do what's easiest unless there's a benefit otherwise, and not typing access specifiers is nice when possible.

也就是说,许多程序员使用这两者来给阅读代码的程序员一个小小的建议:通过使用结构,你巧妙地建议了一个较少封装的面向对象设计。结构体可能在库内部使用 - 在其中了解所有内容是公平的游戏,而类则用于 API 更改会给客户端带来不便并且更好的抽象有用的边界上。这种非常松散的约定源于默认可访问性的差异 - 懒惰/高效/简洁(选择)程序员做最简单的事情,除非有其他好处,并且尽可能不键入访问说明符是好的。

回答by Domonkos Tóth-L?rincz

A class will not publicly inherit from a struct. A struct will publicly inherit from a class or a struct.

类不会从结构公开继承。结构将从类或结构公开继承。

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

B b; b.a=5; //OK. a is accessible

乙乙; ba=5; //好的。a 是可访问的

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

It means the same. B b; b.a=5; //OK. a is accessible

意思是一样的。乙乙; ba=5; //好的。a 是可访问的

struct A
{int a;};
class B : A
{};

B b; b.a=5; //NOT OK. a is NOT accessible

乙乙; ba=5; //不好。a 不可访问

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

B b; b.a=5; //OK. a is accessible

乙乙; ba=5; //好的。a 是可访问的

Finally:

最后:

class A
{int a;};
class B : A
{};

B b; b.a=5; //NOT OK. a is NOT accessible

乙乙; ba=5; //不好。a 不可访问

class A
{int a;};
class B : public A
{};

B b; b.a=5; //NOT OK. a is NOT accessible

乙乙; ba=5; //不好。a 不可访问