【问题标题】:Include headers in header files because of Qt moc由于 Qt moc,在头文件中包含头文件
【发布时间】:2017-06-05 19:18:58
【问题描述】:

我尽量坚持在实现文件中包含头文件而不是在 .h 文件中的原则。但是对于 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,但是当我包含它们的标头时,我显然会遇到多个定义错误。我可以通过只包含 header3.h 来规避这个问题,而 header3.h 又会包含其他标题。 我认为这会导致代码非常混乱,包含不必要的内容和其他不可见的内容(因此容易出错)。我怎样才能做得更好?

【问题讨论】:

  • 如果你得到多个定义错误,你的标题显然有错误。修复它。
  • 您曾尝试过使用#pragma 一次吗?
  • 我建议将您的保单扔进垃圾桶。我建议您在#include 中使用#include 文件来满足声明。例如,如果您的方法之一返回std::string,则将#include <string> 放入您的头文件中。
  • @ThomasMatthews 对于函数声明(即使参数是按值),您只需要前向声明。

标签: c++ qt


【解决方案1】:

你有多个定义,因为可能你在头文件中有一些函数定义,所以将它们移动到相应的 .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 的功能,则需要在文件 other.cpp 中包含“Derived.h”

【讨论】:

    猜你喜欢
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    相关资源
    最近更新 更多