C++ 尝试在mainwindow.cpp之外初始化QSerialPort时,QT给出错误
我正在尝试在QT中进行USB通信。但当我写代码时:C++ 尝试在mainwindow.cpp之外初始化QSerialPort时,QT给出错误,c++,qt,C++,Qt,我正在尝试在QT中进行USB通信。但当我写代码时: #include "usb.h" #include "mainwindow.h" #include <QtSerialPort> #include <QSerialPortInfo> #include <QtSerialPort/QSerialPortInfo> #include <QtSerialPort/QSerialPortInfo> #include
#include "usb.h"
#include "mainwindow.h"
#include <QtSerialPort>
#include <QSerialPortInfo>
#include <QtSerialPort/QSerialPortInfo>
#include <QtSerialPort/QSerialPortInfo>
#include <QSerialPort>
USB::USB()
{
QSerialPort *serial;
serial = new QSerialPort(this);
}
#包括“usb.h”
#包括“mainwindow.h”
#包括
#包括
#包括
#包括
#包括
USB::USB()
{
QSerialPort*系列;
串行=新的QSerialPort(本);
}
在不是我的mainwindow.cpp的某个源中。它给出了“没有用于初始化'QSerialPort'的匹配构造函数”错误。但是当我尝试在mainwindow.cpp中初始化它时,没有错误。所以我猜这些来源中缺少了一些东西
如何消除此错误并在除主窗口之外的任何其他源中打开该串行端口
我对QT和C++也是新手,所以这可能是一个简单的问题,对不起,之前。
< P>你应该声明USB类如下:class USB : public QObject {
Q_OBJECT
public:
USB() : serial(new QSerialPort(this)) {}
private:
QSerialPort *serial;
};
什么是
USB
类QSerialPort
对象不能从任意类中构造。QSerialPort
希望将QObject
作为父类,而您的USB
类则不是。解决方案:创建USB
的QObject
子类。因此,我需要将我的USB类转换为我的MainWindow类的子类。我说得对吗?是否有关于子类、父类和子类的文档?谢谢。请查看这里的资源:成功了。但是我需要在主类中调用这个USB类吗?还是会自动调用?如果是,我如何从我的主类调用它?这只声明了一个类。您需要在某处创建一个实例,并保留一个指向它的引用或指针。部分选项列表:主main
中的局部变量、主main窗口中的字段或其他类、某些类(如主窗口)的静态字段或全局变量。