[英]Why would I need forward class declaration in qt?
在此代碼中:
#ifndef WINDOW_H
#define WINDOW_H
#include <QWidget>
class QPushButton;
class Window : public QWidget
{
public:
explicit Window(QWidget *parent = 0);
private:
QPushButton *m_button;
};
#endif // WINDOW_H
為什么需要轉發類QPushButton聲明? 如果我不這樣做會怎樣? 因為我已經刪除了它,並且程序已經編譯
這是此標頭的.cpp文件:
#include "window.h"
#include <QPushButton>
Window::Window(QWidget *parent) :
QWidget(parent)
{
// Set size of the window
setFixedSize(100, 50);
// Create and position the button
m_button = new QPushButton("Hello World", this);
m_button->setGeometry(10, 10, 80, 30);
}
您在類Window
的聲明中使用了指向QPushButton
的指針。 這就是為什么在使用它之前必須#include <QPushButton>
的原因,或者至少要告訴編譯器它的存在,並使用向前聲明在代碼中進一步聲明它。 如果什么也沒發生,那么從頭文件中刪除前向聲明是因為它包含或聲明了它之前的某處。 可能是qwidget.h,或者其中一個包含的頭文件正在為您執行此操作...,或者在您使用Qt設計器表單的情況下,由“ Qt用戶界面編譯器”生成的.h文件。
但是正如@chris所說:“不要指望標題為您包括其他標題。”
明確地執行此操作沒有額外的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.