在QT GUI中创建全局对象

问题描述 投票:0回答:1

我正在尝试从QT GUI主窗口文件中的类“Fan”创建一个名为x的对象,我希望它在那里是全局的。我希望QT的按钮插槽功能能够对对象执行操作。但是,始终会出现编译器错误“错误:C4430:缺少类型说明符 - 假定的int”。这是头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_btOn_clicked();

    void on_btOff_clicked();

private:
    Ui::MainWindow *ui;
    Fan x; // This doesn't work
    Fan * x; // This doesn't either
    int x; // This does work
};

#endif // MAINWINDOW_H

这是cpp文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "fan.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}
MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btOn_clicked()
{
    ui->lblState->setText("Fan is on");
}

void MainWindow::on_btOff_clicked()
{
    x.turnOff(); // This does not work of course
    x->turnOff(); // Or this
    ui->lblState->setText("Fan is off");
}

我已经告诉cpp文件包含fan.h文件中的Fan类。如果我在窗口构造函数中创建对象,它初始化很好但不是全局的。此外,没有循环包含头文件。粉丝类不包括主窗口。

也许我不知道如何搜索它,但我已经做了一些研究无济于事。任何帮助表示赞赏。

编辑:这是fan.cpp文件

#include "fan.h"

Fan::Fan(){
    speed = 0;
    isOn = false;
}
void Fan::setSpeed(int s){
    speed = s;
}
int Fan::getSpeed(){
    return speed;
}
void Fan::turnOn(){
    isOn = true;
    speed = 1;
}
void Fan::turnOff(){
    isOn = false;
    speed = 0;
}
bool Fan::getState(){
    return isOn;
}

和fan.h文件:

#ifndef FAN_H
#define FAN_H


class Fan
{
private:
    int speed;
    bool isOn;
public:
    Fan();
    void setSpeed(int);
    void turnOn();
    void turnOff();
    int getSpeed();
    bool getState();
};

#endif // FAN_H
c++ qt
1个回答
1
投票

你忘了在Header File中包含或声明Fan类。如果你使用

Fan * x;

你可以用

class Fan;

作为你的Header File开头的前瞻性声明。编译器只需要知道有一个名为Fan的类,但在Header中你只使用一个指针。但是不要忘记#include你的CPP文件中的真实文件。

如果你使用

Fan x;

你必须在你的#include Fan.h Header-File

© www.soinside.com 2019 - 2024. All rights reserved.