带头的循环依赖。使用#ifndef和#define [英] Circular dependencies with headers. Using #ifndef and #define

查看:221
本文介绍了带头的循环依赖。使用#ifndef和#define的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

main.cpp

#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();
}

StartWindow.h

StartWindow.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

MainWindow.h

MainWindow.h

#ifndef MAINWINDOW_H_
#define MAINWINDOW_H_

#include <qdialog.h>
#include "StartWindow.h"

class MainWindow : public QDialog
{
  Q_OBJECT

public:
  MainWindow();
  ~MainWindow();
};
#endif

这会产生错误,因为包含#includeStartWindow.h在MainWindow.h头。但是,我认为使用#ifndef和#define是停止这样的问题?

This produces errors because of the inclusion of #include "StartWindow.h" in the MainWindow.h header. However, I thought the use of #ifndef and #define are to stop problems like this? Can someone clear this up for me?

推荐答案

所谓的头部保护用于防止有点不同类型的错误:包括在一个编译单元中通过不同的间接包含的多个相同的头部。例如,
你在main.cpp中包含ah,然后在main.cpp中包含bh,其中包含ah。

So called "header guards" are used to prevent a bit different kind of error: including same header multiple time through different indirect inclusions in one compile unit. For example, you include "a.h" from main.cpp and then include "b.h" from main.cpp, that includes "a.h" itself somewhere inside.

在你的情况下,两个头文件尝试包括彼此的循环,这是不可能的 - C / C + +预处理器作为简单的文本复制粘贴,这种情况下会发明无限递归的文本插入。

In your case two headers try to include each other circurally, that is not possible - C/C++ preprocessor works as simple text "copy-paste" and this case would invent infinite recursion of text insertion.

我真的不明白为什么你需要StartWindow.h包含在MainWindow.h头文件中。

And I really don't see why would you need "StartWindow.h" inclusion in "MainWindow.h" header.

这篇关于带头的循环依赖。使用#ifndef和#define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆