QT类前置声明

版权声明:原创博文,转载请注明出处! https://blog.csdn.net/sunriver2000/article/details/82819755

在Qt开发项目中,经常会用到各种库,但是一般在.h文件中进行某类型变量定义时,都会对其类型的class进行声明,如下面代码所示:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QCloseEvent>

class QLineEdit;
class QDialog;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public:
    void newFile();
    bool maybeSave();
    bool save();
    bool saveAs();
    bool saveFile(const QString &fileName);
    bool loadFile(const QString &fileName);

private slots:
    void on_actionNew_triggered();
    void on_actionOpen_triggered();
    void on_actionClose_triggered();
    void on_actionSave_triggered();
    void on_actionSaveAs_triggered();
    void on_actionExit_triggered();
    void on_actionUndo_triggered();
    void on_actionCut_triggered();
    void on_actionCopy_triggered();
    void on_actionPaste_triggered();

private:
    Ui::MainWindow *ui;

    bool isUntitled;
    QString curFile;
    
    QLineEdit *findLineEdit;
    QDialog *findDlg;

protected:
    void closeEvent(QCloseEvent *event);
};

#endif // MAINWINDOW_H

前置声明的类定义:

class QLineEdit;
class QDialog;

对象的定义:

 QLineEdit *findLineEdit;
 QDialog *findDlg;

作用:

它们会告诉编译器,我们用到的这些类已经存在了,并且不需要知道这些类的完整定义。

原因:

我们为什么要这样做,而不是将它们的头文件包含进来呢?这主要是由于在程序下文中,我们只是简单的定义了指向这些类的对象的指针,而并没有涉及到该类的其他方面。

优势:

1、是避免了头文件被其他文件多次包含,尤其是在头文件中包含头文件时,容易造成重复包含和产生包含顺序问题,并且增大了文件的体积;

2、提高了编译速度,因为编译器只需知道该类已经被定义了,而无需了解定义的细节。

猜你喜欢

转载自blog.csdn.net/sunriver2000/article/details/82819755