Qt错误:无法在main.cpp中声明多个主窗口

时间:2014-11-03 18:55:46

标签: c++ qt

在" main.cpp":

#include "mainwindow.h"
#include "mainwindow_1.h"

我在main.cpp中编码:

MainWindow *mainWin_1 = new MainWindow;
MainWindow_1 *mainWin_2 = new MainWindow_1;

我已经在" mainwindow.h"中声明了MainWindowMainWindow_1和" mainwindow_1.h"。它们都是QMainWindow。但是当我调试时,我收到一条错误,上面写着" MainWindow_1未在此范围内宣布"。

当我改变时:

 #include "mainwindow.h"
 #include "mainwindow_1.h"

进入

 #include "mainwindow_1.h"
 #include "mainwindow.h"

我收到错误" MainWindow未在此范围内宣布"。

我可以只包含一个主窗口吗?如何在main.cpp中获得两个QMainwindow而不出错?

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDateTime>
#include <ctime>

class MainWindow : public QMainWindow {
    Q_OBJECT;

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

mainwindow_1.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDateTime>
#include <ctime>

class MainWindow_1 : public QMainWindow {
    Q_OBJECT;

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

1 个答案:

答案 0 :(得分:1)

听起来你在两个.h文件中都有相同的包含保护宏。

因此,将其中一个.h文件的开头附近的#ifndef#define更改为与另一个.h文件的包含警卫不同。 例如,将 mainwindow_1.h 更改为:

#ifndef MAINWINDOW_1_H
#define MAINWINDOW_1_H

当你有相同的包含保护宏时,将跳过后面包含的文件的内容,并且其中的类将在该.cpp文件中保持未定义。

要记住的一件事是,C ++包含文件不像“import”或许多其他语言。 #include只是将另一个文件的内容插入到编译中,就像复制粘贴它一样。除此之外,这意味着稍后包含文件“看到”早期包含文件中定义的所有宏,因此包含警卫必须具有唯一名称。

相关问题