[英]Circular dependencies with headers. Using #ifndef and #define
我有以下非常简单的代码:
主文件
#include "ui_library_browser.h"
#include <QtGui/QApplication>
#include "StartWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
StartWindow w;
w.show();
return a.exec();
}
开始窗口.h
#ifndef STARTWINDOW_H_
#define STARTWINDOW_H_
#include <qwidget>
#include "MainWindow.h"
class StartWindow : public QWidget
{
Q_OBJECT
public:
StartWindow();
~StartWindow();
MainWindow main_window; //<-- Problem
};
#endif
主窗口.h
#ifndef MAINWINDOW_H_
#define MAINWINDOW_H_
#include <qdialog.h>
#include "StartWindow.h"
class MainWindow : public QDialog
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
};
#endif
这会产生错误,因为在 MainWindow.h header 中包含 #include "StartWindow.h"。 但是,我认为使用#ifndef 和#define 是为了阻止这样的问题? 有人可以帮我解决这个问题吗?
所谓的“标头保护”用于防止一些不同类型的错误:在一个编译单元中通过不同的间接包含多次包含相同的 header。 例如,您在 main.cpp 中包含“ah”,然后在 main.cpp 中包含“bh”,其中包含“ah”本身。
在您的情况下,两个标题尝试循环地相互包含,这是不可能的 - C/C++ 预处理器作为简单的文本“复制粘贴”工作,这种情况会发明文本插入的无限递归。
而且我真的不明白为什么需要在“MainWindow.h”header 中包含“StartWindow.h”。
您在 MainWindow 中使用 StartWindow 吗? 如果没有,只需删除 StartWindow.h 包含。 否则,使 main_window 成为指针而不是变量。
在文件 StartWindow.h 中删除#include "MainWindow.h"
并添加前向声明(在class StartWindow...
之前):
class MainWindow;
在同一个文件中,将成员MainWindow main_window
更改为
const MainWindow* main_window;
或者
const MainWindow& main_window;
在后一种情况下,您需要在StartWindow
的构造函数中传递const MainWindow&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.