由于QT MOC,将标题包括在标题文件中

Include headers in header files because of Qt moc

本文关键字:标题 包括 文件 QT MOC 由于      更新时间:2023-10-16

我尝试坚持将标题包括在实现文件而不是.h文件中的原理。但是对于QT项目,我必须通过MOC运行大部分标题文件,然后抱怨它不知道的课程。我使用moc header.h -o header.moc.cpp,然后将所有CPP和。 -moc.cpp链接在一起。示例:

header1.h 和一个cpp文件与它一起使用,我在top

上包括header1.h
#ifndef __HEADER_1_H
#define __HEADER_1_H
class Baseclass { /* ... */ };
#endif

header2.h 和一个cpp文件,我在top

上包括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 };

然后,在实现文件中,我需要使用派生和其他文件,但是当我包含他们的标题时,我显然会得到多个定义错误。我可以通过仅包括标题3.H来绕过这一点,该hh.h又将包括其他标题。我认为这会导致非常令人困惑的代码与不必要的包含的内容和其他无形的内容(因此很容易出错(。我该怎么做得更好?

您有多个定义,因为您可能在标题文件中有一些函数定义,因此将它们移至相应的.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 };

在file other.cpp中,如果要使用 Derived

使用功能,则需要包含" dedived.h"。