什么是远期申报?

What is a forward declaration

本文关键字:什么      更新时间:2023-10-16

我不明白带箭头的那一行到底在做什么。这门课包括那门课吗?

#ifndef LINEEDIT_H
#define LINEEDIT_H
#include <QLineEdit>
class QToolButton; <--------------------------------------
class EnchancedLineEdit : public QLineEdit
{
    Q_OBJECT
public:
    EnchancedLineEdit(QWidget *parent = 0);
    ~EnchancedLineEdit();
protected:
  void resizeEvent(QResizeEvent *);
private:
    QToolButton *clearBtn;
private slots:
    void updateCloseButton(const QString &text);
};
#endif // LINEEDIT_H

这是QToolButton类的前向声明(如果你搜索前向声明c++你会发现很多关于这个主题的好搜索结果)

允许使用类QToolButton作为指针和引用,只要QToolButton的成员不在特定的头文件中被访问。

前向声明的目的是加快编译速度。如果不使用前向声明,则需要包含QToolButton的头文件。这意味着,每个包含EnhancedLineEdit头文件的源文件也间接包含QToolButton的头文件,即使源文件本身不使用该类,这将减慢编译过程。

所以只有EnhancedLineEdit的源文件需要包含<QToolButton>。包含EnhancedLineEdit头文件的源文件不需要这样做,除非它们想直接使用QToolButton类。否则,前向声明足以允许在EnhancedLineEdit的头文件中使用指向QToolButton的指针。

这一行

class QToolButton;

在当前(似乎是全局的)命名空间中声明类QToolButton,而不定义类本身。也就是说,这个声明在作用域中引入了类型class QToolButton。这个类用于类EnchancedLineEdit

的定义。
private:
    QToolButton *clearBtn;

事实上,有一行

就足够了
private:
    class QToolButton *clearBtn;
    ^^^^^

,因为它还在当前命名空间中声明了QToolButton类。

这些规范

class QToolButton;

class QToolButton
在此声明class QToolButton *clearBtn;中可能使用的

称为详细类型名。

在代码片段中,您展示了数据成员声明
QToolButton *clearBtn;
在访问class QToolButton的成员之前,

不要求类型QToolButton是完整的。