[英]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.