【问题标题】:Include struct from header包含来自标头的结构
【发布时间】:2015-06-09 10:04:04
【问题描述】:

如何将外部头文件中定义的struct 包含到另一个文件中?起初,我通过指针传递结构,所以我只需要一个前向声明。但现在我想按值传递,不能让它编译。标题lagerverwaltung.h确实包含结构,那么问题出在哪里?

文件lagerverwaltung.h:

#ifndef LAGERVERWALTUNG_H
#define LAGERVERWALTUNG_H

struct etikettInfo{
    QString userName;
    QList<struct properties_content *> inhalte;
};

class Lagerverwaltung : public QMainWindow
{
    Q_OBJECT
    ... and so on
};
#endif // LAGERVERWALTUNG_H

文件etikett1.h:

#ifndef ETIKETT1_H
#define ETIKETT1_H

#include "lagerverwaltung.h" // for struct etikettInfo
class Lagerverwaltung;
//struct etikettInfo;

namespace Ui {
class Etikett1;
}

class Etikett1 : public QMainWindow
{
    Q_OBJECT
public:
    explicit Etikett1(Lagerverwaltung *mainwindow,
                      etikettInfo etikettData,  // <- struct etikettInfo has not been declared
                      QWidget* parent = 0);
    ~Etikett1();

private:
    Ui::Etikett1 *ui;
    Lagerverwaltung *lgrvw;
    etikettInfo etikettData;   // <- struct etikettInfo does not name a type
};

#endif // ETIKETT1_H

如果重要的话:两个 .h 文件都有包含保护。

好的,错误消息(参见代码中的 cmets)确实非常具有描述性,但我不知道我应该做些什么不同。

【问题讨论】:

  • 在 etikett1.h 中包含 lagerverwaltung.h,其中包含 struct etikettInfo 和 class Lagerverwaltung。之后你重新声明class Lagerverwaltung。对我来说,这看起来是件坏事。另外:请发布(相关)错误消息。
  • 错误信息在代码内部(cmets)。
  • 为什么不创建一个文件etikettInfo.h,把结构放在那里,然后把它包含在你需要的地方? (ps:你的英语很强)
  • 好的有效点,但我认为这不会改变任何东西?在这个项目中,我混合了语言,我的错:/
  • @KompjoeFriek:将类重新声明为前向声明并不是一件坏事(它可能表明代码排列不当,但这不是问题)

标签: c++ qt


【解决方案1】:

我也一直在 lagerverwaltung.h 中包含 etikett1.h

这是你的错误。您将etikett1.h 包含在lagerverwaltung.h 中,其中包含etikett1.h,其中包含lagerverwaltung.h 等等。换句话说,你有一个循环依赖。您的包含防护可防止无限包含,但也会导致其中一个标题被包含在另一个标题之前。在这种情况下,首先包含 lagerverwaltung.h,然后再定义任何内容 - 特别是 etikettInfo - 它包括 etikett1.h... 这取决于尚未定义的 etikettInfo。

如果lagerverwaltung.h 真正依赖于etikett1.h,而etikett1.h 唯一依赖于lagerverwaltung.h 是etikettInfo 而lagerverwaltung.h 中没有任何东西依赖于etikettInfo,那么最简单的解决方案是拆分定义的 etikettInfo 到另一个标题中,并将其包含在 etikett1.h 而不是 lagerverwaltung.h 中。

【讨论】:

    【解决方案2】:

    目前情况

    struct etikettInfo{
        QString userName;
        QList<struct properties_content *> inhalte;
    };
    

    需要正确的包含才能使其成为正确声明的结构。所以添加

    #include <QString>
    #include <QList>
    

    以及properties_content的声明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 2013-03-10
      • 2020-03-21
      相关资源
      最近更新 更多