c++ - 在 QT GUI 中创建一个全局对象

标签 c++ qt

我正在尝试从 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

最佳答案

您忘记在头文件 中包含或声明类 Fan。如果你使用

Fan * x;

你可以使用

class Fan;

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

如果你使用

Fan x;

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

关于c++ - 在 QT GUI 中创建一个全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901992/

相关文章:

c++ - Dev-C++ Hello world 不显示

c++ - CUDA 内核函数似乎显示竞争条件,尽管 racecheck 显示 0 竞争条件

c++ - 并行使用主 DNS 服务器和辅助 DNS 服务器进行名称解析

c++ - 派生类中的模板有问题

qt - QPainterPath 与直线的交点(通过 x 求 QPainterPath y)

c++ - Qt 设置 z 或 z-index 的正确方法(以编程方式)

c++ - 小数因子的缩减数组

c++ - 让应用程序在 Windows Phone 8.1 的锁屏下运行

c++ - 如何在 Windows 中读取 CD 音频数据?

c++ - Qt c++ 应用程序抓取