本文介绍了C ++:结构体可以继承一个类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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



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

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

我猜在这种情况下,struct B继承了stuct A中的所有数据。在结构中声明公共/私有成员?



但我注意到:

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

从我的在线C ++手册:

上面的继承是有效的,即使类A有一些成员函数吗?当结构继承它们时,函数会发生什么?反之亦然:从类继承一个结构?



实际上,我有:

  struct user_messages {
std :: list< std :: string>消息;
};

然后我用这个遍历它 foreach message in user_messages.messages



如果我想向我的结构体添加成员函数,我可以改变它的声明并将它提升为一个类,添加函数,然后迭代我的user_messages。消息像以前一样?



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

解决方案

是的,struct可以继承自C ++中的类。 b
$ b

在C ++中,除了关于成员的继承和访问级别的默认行为之外,类和struct是相同的



C ++类




  • 默认继承= 私人

  • 会员变量和函数的默认访问级别= private



C ++ struct




  • 默认继承= public

  • 成员变量和函数的默认访问级别= public


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

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 {};

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?

But I noticed this:

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

From my online C++ manual:

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?

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.

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

解决方案

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

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

C++ class

  • Default Inheritance = private
  • Default Access Level for Member Variables and Functions = private

C++ struct

  • Default Inheritance = public
  • Default Access Level for Member Variables and Functions = public

这篇关于C ++:结构体可以继承一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 21:33