[英]When using inheritance is it necessary to “#include” the header file of child's parent class. C++
I'm working on a multiple inheritance project in C++. 我正在使用C ++开发一个多继承项目。 I have separate files for class definitions (.h) and implementations (.cpp). 我有类定义(.h)和实现(.cpp)的单独文件。 Since this is the first time I've used inheritance in C++ (the rest of our assignments have been in C#) somethings are a little unclear. 因为这是我第一次在C ++中使用继承(我们的其他任务都在C#中),所以有点不清楚。
Do I need to #include "parent.h"
in child.cpp
, or is it sufficient to have defined the inheritance relationship in child.h
ie: 我需要#include "parent.h"
在child.cpp
,还是足以定义的继承关系child.h
即:
class child : parent
{
// child class definition
};
I was warned by an automated prompt that this might be a subjective question, so let me be explicit: I'm asking if this is a functional requirement for the inheritance to work properly, not if it's "good form" or anything along those lines. 我被一个自动提示警告,这可能是一个主观问题,所以让我明确一点:我问这是否是继承正常工作的功能要求 ,而不是它是“良好的形式”还是沿着这些线条的任何东西。
Question 题
Do I need to
#include "parent.h"
inchild.cpp
, or is it sufficient to have defined the inheritance relationship inchild.h
我需要#include "parent.h"
在child.cpp
,还是足以定义的继承关系child.h
Answer 回答
No, you don't need to
#include "parent.h"
inchild.cpp
. 不,你不需要在child.cpp
#include "parent.h"
。 It is sufficient to#include "child.h"
inchild.cpp
. 在child.cpp
#include "child.h"
就足够了。 The contents of"parent.h"
are available inchild.cpp
sincechild.h
already has#include "parent.h"
的内容"parent.h"
在提供child.cpp
自child.h
已经具备#include "parent.h"
Just in case this isn't clear: 以防万一不清楚:
#include
does a simple textual copy, there is no additional logic involved. #include
做了一个简单的文本副本,没有涉及额外的逻辑。
So no, it is not necessary. 所以不,没有必要。 However the reason is not that you have defined the inheritance relation ship, but because #include "parent.h"
in child.h
already copies the text of parent.h
into child.h
and then #include child.h
in child.cpp
, copies the whole text (including the part from parent.h
) there. 但原因并不是你定义了继承关系,而是因为#include "parent.h"
中的#include "parent.h"
已经将parent.h
的文本parent.h
到child.h
,然后在child.h
复制了#include child.h
child.cpp
,复制整个文本(包括parent.h
的部分)。 Another include would be redundant, and without the include guards it would even cause compiler errors. 另一个包含冗余,如果没有包含保护,它甚至会导致编译器错误。
Btw.:Conceptually, your compiler doesn't see the headerfiles as separate entities. 顺便说一下:概念上,您的编译器没有将头文件视为单独的实体。 It sees only a single textstream, which is produced by starting with the cpp file and then executing (recursively) all #include directives. 它只看到一个文本流,它是通过从cpp文件开始然后执行(递归)所有#include指令而产生的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.