我尽量坚持在实现文件中而不是在 .h 文件中包含 header 的原则。但是对于 qt 项目,我必须通过 moc 运行我的大部分头文件,然后它会提示它不知道的类。我使用 moc header.h -o header.moc.cpp
然后将所有 cpp 和 .moc.cpp 链接在一起。
示例:
header1.h 和一个 cpp 文件,我在顶部包含 header1.h
#ifndef __HEADER_1_H
#define __HEADER_1_H
class Baseclass { /* ... */ };
#endif
header2.h 和一个 cpp 文件,我在顶部包含 header1.h 和 header2.h
#ifndef __HEADER_2_H
#define __HEADER_2_H
//here is where I then have to #include "header1.h" because of moc
class Derived: public QObject, public Base { Q_OBJECT; /* ... */ };
#endif
现在的问题是当我在另一个头文件和 cpp 文件中有另一个类时:
header3.h #ifndef __HEADER_3_H #define __HEADER_3_H
//I have to include header2.h because moc doesn't know about Derived.
class Other : public QWidget { Q_OBJECT; Derived* d };
然后在一个实现文件中,我需要使用 Derived 和 Other,但是当我包含它们的 header 时,我显然会遇到多个定义错误。我可以通过仅包含 header3.h 来规避此问题,而 header3.h 又将包含其他 header 。 我认为这会导致非常困惑的代码,其中包含不必要的内容和其他不可见的内容(因此容易出错)。我怎样才能做得更好?
最佳答案
你有多个定义,因为你可能在头文件中有一些函数定义,所以将它们移动到相应的 .cpp 文件中。
现在关于包括: 您需要包含(完整类型)用于继承(不适用于 moc):
#ifndef __HEADER_2_H
#define __HEADER_2_H
//here you need to include header1, because you inherit from that class
//and this needs to see the whole object blueprint
//forward declaration is not enough.
#include <QObject>
#include "Baseclass.h" //or header1.h or whateven the file name is
class Derived: public QObject, public Baseclass { Q_OBJECT; /* ... */ };
#endif
您需要完整的继承类型,对于Derived
,您可以使用前向声明,因为您只有一个指针:
//you need include for QWidget, because you inherit from it
#include <QWidget>
//and forward declaration for derived
Class Derived;
class Other : public QWidget { Q_OBJECT; Derived* d };
如果您想使用 Derived
关于c++ - 由于 Qt moc,在头文件中包含头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376156/